Cycles: Prevent crash in special cases when object has less slots than mesh
[blender.git] / source / blender / blenkernel / intern / 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  * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
19  * All rights reserved.
20  *
21  * Contributor(s): Blender Foundation
22  *
23  * ***** END GPL LICENSE BLOCK *****
24  */
25
26 /** \file blender/blenkernel/intern/mesh.c
27  *  \ingroup bke
28  */
29
30 #include "MEM_guardedalloc.h"
31
32 #include "DNA_scene_types.h"
33 #include "DNA_material_types.h"
34 #include "DNA_meta_types.h"
35 #include "DNA_object_types.h"
36 #include "DNA_key_types.h"
37 #include "DNA_mesh_types.h"
38 #include "DNA_curve_types.h"
39
40 #include "BLI_utildefines.h"
41 #include "BLI_math.h"
42 #include "BLI_listbase.h"
43 #include "BLI_edgehash.h"
44 #include "BLI_string.h"
45
46 #include "BKE_animsys.h"
47 #include "BKE_main.h"
48 #include "BKE_DerivedMesh.h"
49 #include "BKE_global.h"
50 #include "BKE_mesh.h"
51 #include "BKE_displist.h"
52 #include "BKE_library.h"
53 #include "BKE_library_query.h"
54 #include "BKE_library_remap.h"
55 #include "BKE_material.h"
56 #include "BKE_modifier.h"
57 #include "BKE_multires.h"
58 #include "BKE_key.h"
59 #include "BKE_mball.h"
60 #include "BKE_depsgraph.h"
61 /* these 2 are only used by conversion functions */
62 #include "BKE_curve.h"
63 /* -- */
64 #include "BKE_object.h"
65 #include "BKE_editmesh.h"
66
67 #include "DEG_depsgraph.h"
68
69 enum {
70         MESHCMP_DVERT_WEIGHTMISMATCH = 1,
71         MESHCMP_DVERT_GROUPMISMATCH,
72         MESHCMP_DVERT_TOTGROUPMISMATCH,
73         MESHCMP_LOOPCOLMISMATCH,
74         MESHCMP_LOOPUVMISMATCH,
75         MESHCMP_LOOPMISMATCH,
76         MESHCMP_POLYVERTMISMATCH,
77         MESHCMP_POLYMISMATCH,
78         MESHCMP_EDGEUNKNOWN,
79         MESHCMP_VERTCOMISMATCH,
80         MESHCMP_CDLAYERS_MISMATCH
81 };
82
83 static const char *cmpcode_to_str(int code)
84 {
85         switch (code) {
86                 case MESHCMP_DVERT_WEIGHTMISMATCH:
87                         return "Vertex Weight Mismatch";
88                 case MESHCMP_DVERT_GROUPMISMATCH:
89                         return "Vertex Group Mismatch";
90                 case MESHCMP_DVERT_TOTGROUPMISMATCH:
91                         return "Vertex Doesn't Belong To Same Number Of Groups";
92                 case MESHCMP_LOOPCOLMISMATCH:
93                         return "Vertex Color Mismatch";
94                 case MESHCMP_LOOPUVMISMATCH:
95                         return "UV Mismatch";
96                 case MESHCMP_LOOPMISMATCH:
97                         return "Loop Mismatch";
98                 case MESHCMP_POLYVERTMISMATCH:
99                         return "Loop Vert Mismatch In Poly Test";
100                 case MESHCMP_POLYMISMATCH:
101                         return "Loop Vert Mismatch";
102                 case MESHCMP_EDGEUNKNOWN:
103                         return "Edge Mismatch";
104                 case MESHCMP_VERTCOMISMATCH:
105                         return "Vertex Coordinate Mismatch";
106                 case MESHCMP_CDLAYERS_MISMATCH:
107                         return "CustomData Layer Count Mismatch";
108                 default:
109                         return "Mesh Comparison Code Unknown";
110         }
111 }
112
113 /* thresh is threshold for comparing vertices, uvs, vertex colors,
114  * weights, etc.*/
115 static int customdata_compare(CustomData *c1, CustomData *c2, Mesh *m1, Mesh *m2, const float thresh)
116 {
117         const float thresh_sq = thresh * thresh;
118         CustomDataLayer *l1, *l2;
119         int i, i1 = 0, i2 = 0, tot, j;
120         
121         for (i = 0; i < c1->totlayer; i++) {
122                 if (ELEM(c1->layers[i].type, CD_MVERT, CD_MEDGE, CD_MPOLY,
123                          CD_MLOOPUV, CD_MLOOPCOL, CD_MTEXPOLY, CD_MDEFORMVERT))
124                 {
125                         i1++;
126                 }
127         }
128
129         for (i = 0; i < c2->totlayer; i++) {
130                 if (ELEM(c2->layers[i].type, CD_MVERT, CD_MEDGE, CD_MPOLY,
131                          CD_MLOOPUV, CD_MLOOPCOL, CD_MTEXPOLY, CD_MDEFORMVERT))
132                 {
133                         i2++;
134                 }
135         }
136
137         if (i1 != i2)
138                 return MESHCMP_CDLAYERS_MISMATCH;
139         
140         l1 = c1->layers; l2 = c2->layers;
141         tot = i1;
142         i1 = 0; i2 = 0;
143         for (i = 0; i < tot; i++) {
144                 while (i1 < c1->totlayer && !ELEM(l1->type, CD_MVERT, CD_MEDGE, CD_MPOLY,
145                                                   CD_MLOOPUV, CD_MLOOPCOL, CD_MTEXPOLY, CD_MDEFORMVERT))
146                 {
147                         i1++;
148                         l1++;
149                 }
150
151                 while (i2 < c2->totlayer && !ELEM(l2->type, CD_MVERT, CD_MEDGE, CD_MPOLY,
152                                                   CD_MLOOPUV, CD_MLOOPCOL, CD_MTEXPOLY, CD_MDEFORMVERT))
153                 {
154                         i2++;
155                         l2++;
156                 }
157                 
158                 if (l1->type == CD_MVERT) {
159                         MVert *v1 = l1->data;
160                         MVert *v2 = l2->data;
161                         int vtot = m1->totvert;
162                         
163                         for (j = 0; j < vtot; j++, v1++, v2++) {
164                                 if (len_squared_v3v3(v1->co, v2->co) > thresh_sq)
165                                         return MESHCMP_VERTCOMISMATCH;
166                                 /* I don't care about normals, let's just do coodinates */
167                         }
168                 }
169                 
170                 /*we're order-agnostic for edges here*/
171                 if (l1->type == CD_MEDGE) {
172                         MEdge *e1 = l1->data;
173                         MEdge *e2 = l2->data;
174                         int etot = m1->totedge;
175                         EdgeHash *eh = BLI_edgehash_new_ex(__func__, etot);
176                 
177                         for (j = 0; j < etot; j++, e1++) {
178                                 BLI_edgehash_insert(eh, e1->v1, e1->v2, e1);
179                         }
180                         
181                         for (j = 0; j < etot; j++, e2++) {
182                                 if (!BLI_edgehash_lookup(eh, e2->v1, e2->v2))
183                                         return MESHCMP_EDGEUNKNOWN;
184                         }
185                         BLI_edgehash_free(eh, NULL);
186                 }
187                 
188                 if (l1->type == CD_MPOLY) {
189                         MPoly *p1 = l1->data;
190                         MPoly *p2 = l2->data;
191                         int ptot = m1->totpoly;
192                 
193                         for (j = 0; j < ptot; j++, p1++, p2++) {
194                                 MLoop *lp1, *lp2;
195                                 int k;
196                                 
197                                 if (p1->totloop != p2->totloop)
198                                         return MESHCMP_POLYMISMATCH;
199                                 
200                                 lp1 = m1->mloop + p1->loopstart;
201                                 lp2 = m2->mloop + p2->loopstart;
202                                 
203                                 for (k = 0; k < p1->totloop; k++, lp1++, lp2++) {
204                                         if (lp1->v != lp2->v)
205                                                 return MESHCMP_POLYVERTMISMATCH;
206                                 }
207                         }
208                 }
209                 if (l1->type == CD_MLOOP) {
210                         MLoop *lp1 = l1->data;
211                         MLoop *lp2 = l2->data;
212                         int ltot = m1->totloop;
213                 
214                         for (j = 0; j < ltot; j++, lp1++, lp2++) {
215                                 if (lp1->v != lp2->v)
216                                         return MESHCMP_LOOPMISMATCH;
217                         }
218                 }
219                 if (l1->type == CD_MLOOPUV) {
220                         MLoopUV *lp1 = l1->data;
221                         MLoopUV *lp2 = l2->data;
222                         int ltot = m1->totloop;
223                 
224                         for (j = 0; j < ltot; j++, lp1++, lp2++) {
225                                 if (len_squared_v2v2(lp1->uv, lp2->uv) > thresh_sq)
226                                         return MESHCMP_LOOPUVMISMATCH;
227                         }
228                 }
229                 
230                 if (l1->type == CD_MLOOPCOL) {
231                         MLoopCol *lp1 = l1->data;
232                         MLoopCol *lp2 = l2->data;
233                         int ltot = m1->totloop;
234                 
235                         for (j = 0; j < ltot; j++, lp1++, lp2++) {
236                                 if (ABS(lp1->r - lp2->r) > thresh || 
237                                     ABS(lp1->g - lp2->g) > thresh || 
238                                     ABS(lp1->b - lp2->b) > thresh || 
239                                     ABS(lp1->a - lp2->a) > thresh)
240                                 {
241                                         return MESHCMP_LOOPCOLMISMATCH;
242                                 }
243                         }
244                 }
245
246                 if (l1->type == CD_MDEFORMVERT) {
247                         MDeformVert *dv1 = l1->data;
248                         MDeformVert *dv2 = l2->data;
249                         int dvtot = m1->totvert;
250                 
251                         for (j = 0; j < dvtot; j++, dv1++, dv2++) {
252                                 int k;
253                                 MDeformWeight *dw1 = dv1->dw, *dw2 = dv2->dw;
254                                 
255                                 if (dv1->totweight != dv2->totweight)
256                                         return MESHCMP_DVERT_TOTGROUPMISMATCH;
257                                 
258                                 for (k = 0; k < dv1->totweight; k++, dw1++, dw2++) {
259                                         if (dw1->def_nr != dw2->def_nr)
260                                                 return MESHCMP_DVERT_GROUPMISMATCH;
261                                         if (fabsf(dw1->weight - dw2->weight) > thresh)
262                                                 return MESHCMP_DVERT_WEIGHTMISMATCH;
263                                 }
264                         }
265                 }
266         }
267         
268         return 0;
269 }
270
271 /**
272  * Used for unit testing; compares two meshes, checking only
273  * differences we care about.  should be usable with leaf's
274  * testing framework I get RNA work done, will use hackish
275  * testing code for now.
276  */
277 const char *BKE_mesh_cmp(Mesh *me1, Mesh *me2, float thresh)
278 {
279         int c;
280         
281         if (!me1 || !me2)
282                 return "Requires two input meshes";
283         
284         if (me1->totvert != me2->totvert) 
285                 return "Number of verts don't match";
286         
287         if (me1->totedge != me2->totedge)
288                 return "Number of edges don't match";
289         
290         if (me1->totpoly != me2->totpoly)
291                 return "Number of faces don't match";
292                                 
293         if (me1->totloop != me2->totloop)
294                 return "Number of loops don't match";
295         
296         if ((c = customdata_compare(&me1->vdata, &me2->vdata, me1, me2, thresh)))
297                 return cmpcode_to_str(c);
298
299         if ((c = customdata_compare(&me1->edata, &me2->edata, me1, me2, thresh)))
300                 return cmpcode_to_str(c);
301
302         if ((c = customdata_compare(&me1->ldata, &me2->ldata, me1, me2, thresh)))
303                 return cmpcode_to_str(c);
304
305         if ((c = customdata_compare(&me1->pdata, &me2->pdata, me1, me2, thresh)))
306                 return cmpcode_to_str(c);
307         
308         return NULL;
309 }
310
311 static void mesh_ensure_tessellation_customdata(Mesh *me)
312 {
313         if (UNLIKELY((me->totface != 0) && (me->totpoly == 0))) {
314                 /* Pass, otherwise this function  clears 'mface' before
315                  * versioning 'mface -> mpoly' code kicks in [#30583]
316                  *
317                  * Callers could also check but safer to do here - campbell */
318         }
319         else {
320                 const int tottex_original = CustomData_number_of_layers(&me->pdata, CD_MTEXPOLY);
321                 const int totcol_original = CustomData_number_of_layers(&me->ldata, CD_MLOOPCOL);
322
323                 const int tottex_tessface = CustomData_number_of_layers(&me->fdata, CD_MTFACE);
324                 const int totcol_tessface = CustomData_number_of_layers(&me->fdata, CD_MCOL);
325
326                 if (tottex_tessface != tottex_original ||
327                     totcol_tessface != totcol_original)
328                 {
329                         BKE_mesh_tessface_clear(me);
330
331                         CustomData_from_bmeshpoly(&me->fdata, &me->pdata, &me->ldata, me->totface);
332
333                         /* TODO - add some --debug-mesh option */
334                         if (G.debug & G_DEBUG) {
335                                 /* note: this warning may be un-called for if we are initializing the mesh for the
336                                  * first time from bmesh, rather then giving a warning about this we could be smarter
337                                  * and check if there was any data to begin with, for now just print the warning with
338                                  * some info to help troubleshoot whats going on - campbell */
339                                 printf("%s: warning! Tessellation uvs or vcol data got out of sync, "
340                                        "had to reset!\n    CD_MTFACE: %d != CD_MTEXPOLY: %d || CD_MCOL: %d != CD_MLOOPCOL: %d\n",
341                                        __func__, tottex_tessface, tottex_original, totcol_tessface, totcol_original);
342                         }
343                 }
344         }
345 }
346
347 void BKE_mesh_ensure_skin_customdata(Mesh *me)
348 {
349         BMesh *bm = me->edit_btmesh ? me->edit_btmesh->bm : NULL;
350         MVertSkin *vs;
351
352         if (bm) {
353                 if (!CustomData_has_layer(&bm->vdata, CD_MVERT_SKIN)) {
354                         BMVert *v;
355                         BMIter iter;
356
357                         BM_data_layer_add(bm, &bm->vdata, CD_MVERT_SKIN);
358
359                         /* Mark an arbitrary vertex as root */
360                         BM_ITER_MESH (v, &iter, bm, BM_VERTS_OF_MESH) {
361                                 vs = CustomData_bmesh_get(&bm->vdata, v->head.data,
362                                                           CD_MVERT_SKIN);
363                                 vs->flag |= MVERT_SKIN_ROOT;
364                                 break;
365                         }
366                 }
367         }
368         else {
369                 if (!CustomData_has_layer(&me->vdata, CD_MVERT_SKIN)) {
370                         vs = CustomData_add_layer(&me->vdata,
371                                                   CD_MVERT_SKIN,
372                                                   CD_DEFAULT,
373                                                   NULL,
374                                                   me->totvert);
375
376                         /* Mark an arbitrary vertex as root */
377                         if (vs) {
378                                 vs->flag |= MVERT_SKIN_ROOT;
379                         }
380                 }
381         }
382 }
383
384 /* this ensures grouped customdata (e.g. mtexpoly and mloopuv and mtface, or
385  * mloopcol and mcol) have the same relative active/render/clone/mask indices.
386  *
387  * note that for undo mesh data we want to skip 'ensure_tess_cd' call since
388  * we don't want to store memory for tessface when its only used for older
389  * versions of the mesh. - campbell*/
390 static void mesh_update_linked_customdata(Mesh *me, const bool do_ensure_tess_cd)
391 {
392         if (me->edit_btmesh)
393                 BKE_editmesh_update_linked_customdata(me->edit_btmesh);
394
395         if (do_ensure_tess_cd) {
396                 mesh_ensure_tessellation_customdata(me);
397         }
398
399         CustomData_bmesh_update_active_layers(&me->fdata, &me->pdata, &me->ldata);
400 }
401
402 void BKE_mesh_update_customdata_pointers(Mesh *me, const bool do_ensure_tess_cd)
403 {
404         mesh_update_linked_customdata(me, do_ensure_tess_cd);
405
406         me->mvert = CustomData_get_layer(&me->vdata, CD_MVERT);
407         me->dvert = CustomData_get_layer(&me->vdata, CD_MDEFORMVERT);
408
409         me->medge = CustomData_get_layer(&me->edata, CD_MEDGE);
410
411         me->mface = CustomData_get_layer(&me->fdata, CD_MFACE);
412         me->mcol = CustomData_get_layer(&me->fdata, CD_MCOL);
413         me->mtface = CustomData_get_layer(&me->fdata, CD_MTFACE);
414         
415         me->mpoly = CustomData_get_layer(&me->pdata, CD_MPOLY);
416         me->mloop = CustomData_get_layer(&me->ldata, CD_MLOOP);
417
418         me->mtpoly = CustomData_get_layer(&me->pdata, CD_MTEXPOLY);
419         me->mloopcol = CustomData_get_layer(&me->ldata, CD_MLOOPCOL);
420         me->mloopuv = CustomData_get_layer(&me->ldata, CD_MLOOPUV);
421 }
422
423 bool BKE_mesh_has_custom_loop_normals(Mesh *me)
424 {
425         if (me->edit_btmesh) {
426                 return CustomData_has_layer(&me->edit_btmesh->bm->ldata, CD_CUSTOMLOOPNORMAL);
427         }
428         else {
429                 return CustomData_has_layer(&me->ldata, CD_CUSTOMLOOPNORMAL);
430         }
431 }
432
433 /** Free (or release) any data used by this mesh (does not free the mesh itself). */
434 void BKE_mesh_free(Mesh *me)
435 {
436         BKE_animdata_free(&me->id, false);
437
438         CustomData_free(&me->vdata, me->totvert);
439         CustomData_free(&me->edata, me->totedge);
440         CustomData_free(&me->fdata, me->totface);
441         CustomData_free(&me->ldata, me->totloop);
442         CustomData_free(&me->pdata, me->totpoly);
443
444         MEM_SAFE_FREE(me->mat);
445         MEM_SAFE_FREE(me->bb);
446         MEM_SAFE_FREE(me->mselect);
447         MEM_SAFE_FREE(me->edit_btmesh);
448 }
449
450 static void mesh_tessface_clear_intern(Mesh *mesh, int free_customdata)
451 {
452         if (free_customdata) {
453                 CustomData_free(&mesh->fdata, mesh->totface);
454         }
455         else {
456                 CustomData_reset(&mesh->fdata);
457         }
458
459         mesh->mface = NULL;
460         mesh->mtface = NULL;
461         mesh->mcol = NULL;
462         mesh->totface = 0;
463 }
464
465 void BKE_mesh_init(Mesh *me)
466 {
467         BLI_assert(MEMCMP_STRUCT_OFS_IS_ZERO(me, id));
468
469         me->size[0] = me->size[1] = me->size[2] = 1.0;
470         me->smoothresh = DEG2RADF(30);
471         me->texflag = ME_AUTOSPACE;
472
473         /* disable because its slow on many GPU's, see [#37518] */
474 #if 0
475         me->flag = ME_TWOSIDED;
476 #endif
477         me->drawflag = ME_DRAWEDGES | ME_DRAWFACES | ME_DRAWCREASES;
478
479         CustomData_reset(&me->vdata);
480         CustomData_reset(&me->edata);
481         CustomData_reset(&me->fdata);
482         CustomData_reset(&me->pdata);
483         CustomData_reset(&me->ldata);
484 }
485
486 Mesh *BKE_mesh_add(Main *bmain, const char *name)
487 {
488         Mesh *me;
489
490         me = BKE_libblock_alloc(bmain, ID_ME, name);
491
492         BKE_mesh_init(me);
493
494         return me;
495 }
496
497 Mesh *BKE_mesh_copy(Main *bmain, Mesh *me)
498 {
499         Mesh *men;
500         int a;
501         const int do_tessface = ((me->totface != 0) && (me->totpoly == 0)); /* only do tessface if we have no polys */
502         
503         men = BKE_libblock_copy(bmain, &me->id);
504         
505         men->mat = MEM_dupallocN(me->mat);
506         for (a = 0; a < men->totcol; a++) {
507                 id_us_plus((ID *)men->mat[a]);
508         }
509         id_us_plus((ID *)men->texcomesh);
510
511         CustomData_copy(&me->vdata, &men->vdata, CD_MASK_MESH, CD_DUPLICATE, men->totvert);
512         CustomData_copy(&me->edata, &men->edata, CD_MASK_MESH, CD_DUPLICATE, men->totedge);
513         CustomData_copy(&me->ldata, &men->ldata, CD_MASK_MESH, CD_DUPLICATE, men->totloop);
514         CustomData_copy(&me->pdata, &men->pdata, CD_MASK_MESH, CD_DUPLICATE, men->totpoly);
515         if (do_tessface) {
516                 CustomData_copy(&me->fdata, &men->fdata, CD_MASK_MESH, CD_DUPLICATE, men->totface);
517         }
518         else {
519                 mesh_tessface_clear_intern(men, false);
520         }
521
522         BKE_mesh_update_customdata_pointers(men, do_tessface);
523
524         men->edit_btmesh = NULL;
525
526         men->mselect = MEM_dupallocN(men->mselect);
527         men->bb = MEM_dupallocN(men->bb);
528
529         if (me->key) {
530                 men->key = BKE_key_copy(bmain, me->key);
531                 men->key->from = (ID *)men;
532         }
533
534         BKE_id_copy_ensure_local(bmain, &me->id, &men->id);
535
536         return men;
537 }
538
539 BMesh *BKE_mesh_to_bmesh(
540         Mesh *me, Object *ob,
541         const bool add_key_index, const struct BMeshCreateParams *params)
542 {
543         BMesh *bm;
544         const BMAllocTemplate allocsize = BMALLOC_TEMPLATE_FROM_ME(me);
545
546         bm = BM_mesh_create(&allocsize, params);
547
548         BM_mesh_bm_from_me(
549                 bm, me, (&(struct BMeshFromMeshParams){
550                     .add_key_index = add_key_index, .use_shapekey = true, .active_shapekey = ob->shapenr,
551                 }));
552
553         return bm;
554 }
555
556 void BKE_mesh_make_local(Main *bmain, Mesh *me, const bool lib_local)
557 {
558         BKE_id_make_local_generic(bmain, &me->id, true, lib_local);
559 }
560
561 bool BKE_mesh_uv_cdlayer_rename_index(Mesh *me, const int poly_index, const int loop_index, const int face_index,
562                                       const char *new_name, const bool do_tessface)
563 {
564         CustomData *pdata, *ldata, *fdata;
565         CustomDataLayer *cdlp, *cdlu, *cdlf;
566         const int step = do_tessface ? 3 : 2;
567         int i;
568
569         if (me->edit_btmesh) {
570                 pdata = &me->edit_btmesh->bm->pdata;
571                 ldata = &me->edit_btmesh->bm->ldata;
572                 fdata = NULL;  /* No tessellated data in BMesh! */
573         }
574         else {
575                 pdata = &me->pdata;
576                 ldata = &me->ldata;
577                 fdata = &me->fdata;
578         }
579         cdlp = &pdata->layers[poly_index];
580         cdlu = &ldata->layers[loop_index];
581         cdlf = fdata && do_tessface ? &fdata->layers[face_index] : NULL;
582
583         if (cdlp->name != new_name) {
584                 /* Mesh validate passes a name from the CD layer as the new name,
585                  * Avoid memcpy from self to self in this case.
586                  */
587                 BLI_strncpy(cdlp->name, new_name, sizeof(cdlp->name));
588                 CustomData_set_layer_unique_name(pdata, cdlp - pdata->layers);
589         }
590
591         /* Loop until we do have exactly the same name for all layers! */
592         for (i = 1; !STREQ(cdlp->name, cdlu->name) || (cdlf && !STREQ(cdlp->name, cdlf->name)); i++) {
593                 switch (i % step) {
594                         case 0:
595                                 BLI_strncpy(cdlp->name, cdlu->name, sizeof(cdlp->name));
596                                 CustomData_set_layer_unique_name(pdata, cdlp - pdata->layers);
597                                 break;
598                         case 1:
599                                 BLI_strncpy(cdlu->name, cdlp->name, sizeof(cdlu->name));
600                                 CustomData_set_layer_unique_name(ldata, cdlu - ldata->layers);
601                                 break;
602                         case 2:
603                                 if (cdlf) {
604                                         BLI_strncpy(cdlf->name, cdlp->name, sizeof(cdlf->name));
605                                         CustomData_set_layer_unique_name(fdata, cdlf - fdata->layers);
606                                 }
607                                 break;
608                 }
609         }
610
611         return true;
612 }
613
614 bool BKE_mesh_uv_cdlayer_rename(Mesh *me, const char *old_name, const char *new_name, bool do_tessface)
615 {
616         CustomData *pdata, *ldata, *fdata;
617         if (me->edit_btmesh) {
618                 pdata = &me->edit_btmesh->bm->pdata;
619                 ldata = &me->edit_btmesh->bm->ldata;
620                 /* No tessellated data in BMesh! */
621                 fdata = NULL;
622                 do_tessface = false;
623         }
624         else {
625                 pdata = &me->pdata;
626                 ldata = &me->ldata;
627                 fdata = &me->fdata;
628                 do_tessface = (do_tessface && fdata->totlayer);
629         }
630
631         {
632                 const int pidx_start = CustomData_get_layer_index(pdata, CD_MTEXPOLY);
633                 const int lidx_start = CustomData_get_layer_index(ldata, CD_MLOOPUV);
634                 const int fidx_start = do_tessface ? CustomData_get_layer_index(fdata, CD_MTFACE) : -1;
635                 int pidx = CustomData_get_named_layer(pdata, CD_MTEXPOLY, old_name);
636                 int lidx = CustomData_get_named_layer(ldata, CD_MLOOPUV, old_name);
637                 int fidx = do_tessface ? CustomData_get_named_layer(fdata, CD_MTFACE, old_name) : -1;
638
639                 /* None of those cases should happen, in theory!
640                  * Note this assume we have the same number of mtexpoly, mloopuv and mtface layers!
641                  */
642                 if (pidx == -1) {
643                         if (lidx == -1) {
644                                 if (fidx == -1) {
645                                         /* No layer found with this name! */
646                                         return false;
647                                 }
648                                 else {
649                                         lidx = fidx;
650                                 }
651                         }
652                         pidx = lidx;
653                 }
654                 else {
655                         if (lidx == -1) {
656                                 lidx = pidx;
657                         }
658                         if (fidx == -1 && do_tessface) {
659                                 fidx = pidx;
660                         }
661                 }
662 #if 0
663                 /* For now, we do not consider mismatch in indices (i.e. same name leading to (relative) different indices). */
664                 else if (pidx != lidx) {
665                         lidx = pidx;
666                 }
667 #endif
668
669                 /* Go back to absolute indices! */
670                 pidx += pidx_start;
671                 lidx += lidx_start;
672                 if (fidx != -1)
673                         fidx += fidx_start;
674
675                 return BKE_mesh_uv_cdlayer_rename_index(me, pidx, lidx, fidx, new_name, do_tessface);
676         }
677 }
678
679 void BKE_mesh_boundbox_calc(Mesh *me, float r_loc[3], float r_size[3])
680 {
681         BoundBox *bb;
682         float min[3], max[3];
683         float mloc[3], msize[3];
684         
685         if (me->bb == NULL) me->bb = MEM_callocN(sizeof(BoundBox), "boundbox");
686         bb = me->bb;
687
688         if (!r_loc) r_loc = mloc;
689         if (!r_size) r_size = msize;
690         
691         INIT_MINMAX(min, max);
692         if (!BKE_mesh_minmax(me, min, max)) {
693                 min[0] = min[1] = min[2] = -1.0f;
694                 max[0] = max[1] = max[2] = 1.0f;
695         }
696
697         mid_v3_v3v3(r_loc, min, max);
698                 
699         r_size[0] = (max[0] - min[0]) / 2.0f;
700         r_size[1] = (max[1] - min[1]) / 2.0f;
701         r_size[2] = (max[2] - min[2]) / 2.0f;
702         
703         BKE_boundbox_init_from_minmax(bb, min, max);
704
705         bb->flag &= ~BOUNDBOX_DIRTY;
706 }
707
708 void BKE_mesh_texspace_calc(Mesh *me)
709 {
710         float loc[3], size[3];
711         int a;
712
713         BKE_mesh_boundbox_calc(me, loc, size);
714
715         if (me->texflag & ME_AUTOSPACE) {
716                 for (a = 0; a < 3; a++) {
717                         if (size[a] == 0.0f) size[a] = 1.0f;
718                         else if (size[a] > 0.0f && size[a] < 0.00001f) size[a] = 0.00001f;
719                         else if (size[a] < 0.0f && size[a] > -0.00001f) size[a] = -0.00001f;
720                 }
721
722                 copy_v3_v3(me->loc, loc);
723                 copy_v3_v3(me->size, size);
724                 zero_v3(me->rot);
725         }
726 }
727
728 BoundBox *BKE_mesh_boundbox_get(Object *ob)
729 {
730         Mesh *me = ob->data;
731
732         if (ob->bb)
733                 return ob->bb;
734
735         if (me->bb == NULL || (me->bb->flag & BOUNDBOX_DIRTY)) {
736                 BKE_mesh_texspace_calc(me);
737         }
738
739         return me->bb;
740 }
741
742 void BKE_mesh_texspace_get(Mesh *me, float r_loc[3], float r_rot[3], float r_size[3])
743 {
744         if (me->bb == NULL || (me->bb->flag & BOUNDBOX_DIRTY)) {
745                 BKE_mesh_texspace_calc(me);
746         }
747
748         if (r_loc) copy_v3_v3(r_loc,  me->loc);
749         if (r_rot) copy_v3_v3(r_rot,  me->rot);
750         if (r_size) copy_v3_v3(r_size, me->size);
751 }
752
753 void BKE_mesh_texspace_copy_from_object(Mesh *me, Object *ob)
754 {
755         float *texloc, *texrot, *texsize;
756         short *texflag;
757
758         if (BKE_object_obdata_texspace_get(ob, &texflag, &texloc, &texsize, &texrot)) {
759                 me->texflag = *texflag;
760                 copy_v3_v3(me->loc, texloc);
761                 copy_v3_v3(me->size, texsize);
762                 copy_v3_v3(me->rot, texrot);
763         }
764 }
765
766 float (*BKE_mesh_orco_verts_get(Object *ob))[3]
767 {
768         Mesh *me = ob->data;
769         MVert *mvert = NULL;
770         Mesh *tme = me->texcomesh ? me->texcomesh : me;
771         int a, totvert;
772         float (*vcos)[3] = NULL;
773
774         /* Get appropriate vertex coordinates */
775         vcos = MEM_callocN(sizeof(*vcos) * me->totvert, "orco mesh");
776         mvert = tme->mvert;
777         totvert = min_ii(tme->totvert, me->totvert);
778
779         for (a = 0; a < totvert; a++, mvert++) {
780                 copy_v3_v3(vcos[a], mvert->co);
781         }
782
783         return vcos;
784 }
785
786 void BKE_mesh_orco_verts_transform(Mesh *me, float (*orco)[3], int totvert, int invert)
787 {
788         float loc[3], size[3];
789         int a;
790
791         BKE_mesh_texspace_get(me->texcomesh ? me->texcomesh : me, loc, NULL, size);
792
793         if (invert) {
794                 for (a = 0; a < totvert; a++) {
795                         float *co = orco[a];
796                         madd_v3_v3v3v3(co, loc, co, size);
797                 }
798         }
799         else {
800                 for (a = 0; a < totvert; a++) {
801                         float *co = orco[a];
802                         co[0] = (co[0] - loc[0]) / size[0];
803                         co[1] = (co[1] - loc[1]) / size[1];
804                         co[2] = (co[2] - loc[2]) / size[2];
805                 }
806         }
807 }
808
809 /* rotates the vertices of a face in case v[2] or v[3] (vertex index) is = 0.
810  * this is necessary to make the if (mface->v4) check for quads work */
811 int test_index_face(MFace *mface, CustomData *fdata, int mfindex, int nr)
812 {
813         /* first test if the face is legal */
814         if ((mface->v3 || nr == 4) && mface->v3 == mface->v4) {
815                 mface->v4 = 0;
816                 nr--;
817         }
818         if ((mface->v2 || mface->v4) && mface->v2 == mface->v3) {
819                 mface->v3 = mface->v4;
820                 mface->v4 = 0;
821                 nr--;
822         }
823         if (mface->v1 == mface->v2) {
824                 mface->v2 = mface->v3;
825                 mface->v3 = mface->v4;
826                 mface->v4 = 0;
827                 nr--;
828         }
829
830         /* check corrupt cases, bow-tie geometry, cant handle these because edge data wont exist so just return 0 */
831         if (nr == 3) {
832                 if (
833                     /* real edges */
834                     mface->v1 == mface->v2 ||
835                     mface->v2 == mface->v3 ||
836                     mface->v3 == mface->v1)
837                 {
838                         return 0;
839                 }
840         }
841         else if (nr == 4) {
842                 if (
843                     /* real edges */
844                     mface->v1 == mface->v2 ||
845                     mface->v2 == mface->v3 ||
846                     mface->v3 == mface->v4 ||
847                     mface->v4 == mface->v1 ||
848                     /* across the face */
849                     mface->v1 == mface->v3 ||
850                     mface->v2 == mface->v4)
851                 {
852                         return 0;
853                 }
854         }
855
856         /* prevent a zero at wrong index location */
857         if (nr == 3) {
858                 if (mface->v3 == 0) {
859                         static int corner_indices[4] = {1, 2, 0, 3};
860
861                         SWAP(unsigned int, mface->v1, mface->v2);
862                         SWAP(unsigned int, mface->v2, mface->v3);
863
864                         if (fdata)
865                                 CustomData_swap_corners(fdata, mfindex, corner_indices);
866                 }
867         }
868         else if (nr == 4) {
869                 if (mface->v3 == 0 || mface->v4 == 0) {
870                         static int corner_indices[4] = {2, 3, 0, 1};
871
872                         SWAP(unsigned int, mface->v1, mface->v3);
873                         SWAP(unsigned int, mface->v2, mface->v4);
874
875                         if (fdata)
876                                 CustomData_swap_corners(fdata, mfindex, corner_indices);
877                 }
878         }
879
880         return nr;
881 }
882
883 Mesh *BKE_mesh_from_object(Object *ob)
884 {
885         
886         if (ob == NULL) return NULL;
887         if (ob->type == OB_MESH) return ob->data;
888         else return NULL;
889 }
890
891 void BKE_mesh_assign_object(Object *ob, Mesh *me)
892 {
893         Mesh *old = NULL;
894
895         multires_force_update(ob);
896         
897         if (ob == NULL) return;
898         
899         if (ob->type == OB_MESH) {
900                 old = ob->data;
901                 if (old)
902                         id_us_min(&old->id);
903                 ob->data = me;
904                 id_us_plus((ID *)me);
905         }
906         
907         test_object_materials(ob, (ID *)me);
908
909         test_object_modifiers(ob);
910 }
911
912 void BKE_mesh_from_metaball(ListBase *lb, Mesh *me)
913 {
914         DispList *dl;
915         MVert *mvert;
916         MLoop *mloop, *allloop;
917         MPoly *mpoly;
918         const float *nors, *verts;
919         int a, *index;
920         
921         dl = lb->first;
922         if (dl == NULL) return;
923
924         if (dl->type == DL_INDEX4) {
925                 mvert = CustomData_add_layer(&me->vdata, CD_MVERT, CD_CALLOC, NULL, dl->nr);
926                 allloop = mloop = CustomData_add_layer(&me->ldata, CD_MLOOP, CD_CALLOC, NULL, dl->parts * 4);
927                 mpoly = CustomData_add_layer(&me->pdata, CD_MPOLY, CD_CALLOC, NULL, dl->parts);
928                 me->mvert = mvert;
929                 me->mloop = mloop;
930                 me->mpoly = mpoly;
931                 me->totvert = dl->nr;
932                 me->totpoly = dl->parts;
933
934                 a = dl->nr;
935                 nors = dl->nors;
936                 verts = dl->verts;
937                 while (a--) {
938                         copy_v3_v3(mvert->co, verts);
939                         normal_float_to_short_v3(mvert->no, nors);
940                         mvert++;
941                         nors += 3;
942                         verts += 3;
943                 }
944                 
945                 a = dl->parts;
946                 index = dl->index;
947                 while (a--) {
948                         int count = index[2] != index[3] ? 4 : 3;
949
950                         mloop[0].v = index[0];
951                         mloop[1].v = index[1];
952                         mloop[2].v = index[2];
953                         if (count == 4)
954                                 mloop[3].v = index[3];
955
956                         mpoly->totloop = count;
957                         mpoly->loopstart = (int)(mloop - allloop);
958                         mpoly->flag = ME_SMOOTH;
959
960
961                         mpoly++;
962                         mloop += count;
963                         me->totloop += count;
964                         index += 4;
965                 }
966
967                 BKE_mesh_update_customdata_pointers(me, true);
968
969                 BKE_mesh_calc_normals(me);
970
971                 BKE_mesh_calc_edges(me, true, false);
972         }
973 }
974
975 /**
976  * Specialized function to use when we _know_ existing edges don't overlap with poly edges.
977  */
978 static void make_edges_mdata_extend(MEdge **r_alledge, int *r_totedge,
979                                     const MPoly *mpoly, MLoop *mloop,
980                                     const int totpoly)
981 {
982         int totedge = *r_totedge;
983         int totedge_new;
984         EdgeHash *eh;
985         unsigned int eh_reserve;
986         const MPoly *mp;
987         int i;
988
989         eh_reserve = max_ii(totedge, BLI_EDGEHASH_SIZE_GUESS_FROM_POLYS(totpoly));
990         eh = BLI_edgehash_new_ex(__func__, eh_reserve);
991
992         for (i = 0, mp = mpoly; i < totpoly; i++, mp++) {
993                 BKE_mesh_poly_edgehash_insert(eh, mp, mloop + mp->loopstart);
994         }
995
996         totedge_new = BLI_edgehash_size(eh);
997
998 #ifdef DEBUG
999         /* ensure that theres no overlap! */
1000         if (totedge_new) {
1001                 MEdge *medge = *r_alledge;
1002                 for (i = 0; i < totedge; i++, medge++) {
1003                         BLI_assert(BLI_edgehash_haskey(eh, medge->v1, medge->v2) == false);
1004                 }
1005         }
1006 #endif
1007
1008         if (totedge_new) {
1009                 EdgeHashIterator *ehi;
1010                 MEdge *medge;
1011                 unsigned int e_index = totedge;
1012
1013                 *r_alledge = medge = (*r_alledge ? MEM_reallocN(*r_alledge, sizeof(MEdge) * (totedge + totedge_new)) :
1014                                                    MEM_callocN(sizeof(MEdge) * totedge_new, __func__));
1015                 medge += totedge;
1016
1017                 totedge += totedge_new;
1018
1019                 /* --- */
1020                 for (ehi = BLI_edgehashIterator_new(eh);
1021                      BLI_edgehashIterator_isDone(ehi) == false;
1022                      BLI_edgehashIterator_step(ehi), ++medge, e_index++)
1023                 {
1024                         BLI_edgehashIterator_getKey(ehi, &medge->v1, &medge->v2);
1025                         BLI_edgehashIterator_setValue(ehi, SET_UINT_IN_POINTER(e_index));
1026
1027                         medge->crease = medge->bweight = 0;
1028                         medge->flag = ME_EDGEDRAW | ME_EDGERENDER;
1029                 }
1030                 BLI_edgehashIterator_free(ehi);
1031
1032                 *r_totedge = totedge;
1033
1034
1035                 for (i = 0, mp = mpoly; i < totpoly; i++, mp++) {
1036                         MLoop *l = &mloop[mp->loopstart];
1037                         MLoop *l_prev = (l + (mp->totloop - 1));
1038                         int j;
1039                         for (j = 0; j < mp->totloop; j++, l++) {
1040                                 /* lookup hashed edge index */
1041                                 l_prev->e = GET_UINT_FROM_POINTER(BLI_edgehash_lookup(eh, l_prev->v, l->v));
1042                                 l_prev = l;
1043                         }
1044                 }
1045         }
1046
1047         BLI_edgehash_free(eh, NULL);
1048 }
1049
1050
1051 /* Initialize mverts, medges and, faces for converting nurbs to mesh and derived mesh */
1052 /* return non-zero on error */
1053 int BKE_mesh_nurbs_to_mdata(
1054         Object *ob, MVert **r_allvert, int *r_totvert,
1055         MEdge **r_alledge, int *r_totedge, MLoop **r_allloop, MPoly **r_allpoly,
1056         int *r_totloop, int *r_totpoly)
1057 {
1058         ListBase disp = {NULL, NULL};
1059
1060         if (ob->curve_cache) {
1061                 disp = ob->curve_cache->disp;
1062         }
1063
1064         return BKE_mesh_nurbs_displist_to_mdata(
1065                 ob, &disp,
1066                 r_allvert, r_totvert,
1067                 r_alledge, r_totedge,
1068                 r_allloop, r_allpoly, NULL,
1069                 r_totloop, r_totpoly);
1070 }
1071
1072 /* BMESH: this doesn't calculate all edges from polygons,
1073  * only free standing edges are calculated */
1074
1075 /* Initialize mverts, medges and, faces for converting nurbs to mesh and derived mesh */
1076 /* use specified dispbase */
1077 int BKE_mesh_nurbs_displist_to_mdata(
1078         Object *ob, const ListBase *dispbase,
1079         MVert **r_allvert, int *r_totvert,
1080         MEdge **r_alledge, int *r_totedge,
1081         MLoop **r_allloop, MPoly **r_allpoly,
1082         MLoopUV **r_alluv,
1083         int *r_totloop, int *r_totpoly)
1084 {
1085         Curve *cu = ob->data;
1086         DispList *dl;
1087         MVert *mvert;
1088         MPoly *mpoly;
1089         MLoop *mloop;
1090         MLoopUV *mloopuv = NULL;
1091         MEdge *medge;
1092         const float *data;
1093         int a, b, ofs, vertcount, startvert, totvert = 0, totedge = 0, totloop = 0, totvlak = 0;
1094         int p1, p2, p3, p4, *index;
1095         const bool conv_polys = ((CU_DO_2DFILL(cu) == false) ||  /* 2d polys are filled with DL_INDEX3 displists */
1096                                  (ob->type == OB_SURF));  /* surf polys are never filled */
1097
1098         /* count */
1099         dl = dispbase->first;
1100         while (dl) {
1101                 if (dl->type == DL_SEGM) {
1102                         totvert += dl->parts * dl->nr;
1103                         totedge += dl->parts * (dl->nr - 1);
1104                 }
1105                 else if (dl->type == DL_POLY) {
1106                         if (conv_polys) {
1107                                 totvert += dl->parts * dl->nr;
1108                                 totedge += dl->parts * dl->nr;
1109                         }
1110                 }
1111                 else if (dl->type == DL_SURF) {
1112                         int tot;
1113                         totvert += dl->parts * dl->nr;
1114                         tot = (dl->parts - 1 + ((dl->flag & DL_CYCL_V) == 2)) * (dl->nr - 1 + (dl->flag & DL_CYCL_U));
1115                         totvlak += tot;
1116                         totloop += tot * 4;
1117                 }
1118                 else if (dl->type == DL_INDEX3) {
1119                         int tot;
1120                         totvert += dl->nr;
1121                         tot = dl->parts;
1122                         totvlak += tot;
1123                         totloop += tot * 3;
1124                 }
1125                 dl = dl->next;
1126         }
1127
1128         if (totvert == 0) {
1129                 /* error("can't convert"); */
1130                 /* Make Sure you check ob->data is a curve */
1131                 return -1;
1132         }
1133
1134         *r_allvert = mvert = MEM_callocN(sizeof(MVert) * totvert, "nurbs_init mvert");
1135         *r_alledge = medge = MEM_callocN(sizeof(MEdge) * totedge, "nurbs_init medge");
1136         *r_allloop = mloop = MEM_callocN(sizeof(MLoop) * totvlak * 4, "nurbs_init mloop"); // totloop
1137         *r_allpoly = mpoly = MEM_callocN(sizeof(MPoly) * totvlak, "nurbs_init mloop");
1138
1139         if (r_alluv)
1140                 *r_alluv = mloopuv = MEM_callocN(sizeof(MLoopUV) * totvlak * 4, "nurbs_init mloopuv");
1141         
1142         /* verts and faces */
1143         vertcount = 0;
1144
1145         dl = dispbase->first;
1146         while (dl) {
1147                 const bool is_smooth = (dl->rt & CU_SMOOTH) != 0;
1148
1149                 if (dl->type == DL_SEGM) {
1150                         startvert = vertcount;
1151                         a = dl->parts * dl->nr;
1152                         data = dl->verts;
1153                         while (a--) {
1154                                 copy_v3_v3(mvert->co, data);
1155                                 data += 3;
1156                                 vertcount++;
1157                                 mvert++;
1158                         }
1159
1160                         for (a = 0; a < dl->parts; a++) {
1161                                 ofs = a * dl->nr;
1162                                 for (b = 1; b < dl->nr; b++) {
1163                                         medge->v1 = startvert + ofs + b - 1;
1164                                         medge->v2 = startvert + ofs + b;
1165                                         medge->flag = ME_LOOSEEDGE | ME_EDGERENDER | ME_EDGEDRAW;
1166
1167                                         medge++;
1168                                 }
1169                         }
1170
1171                 }
1172                 else if (dl->type == DL_POLY) {
1173                         if (conv_polys) {
1174                                 startvert = vertcount;
1175                                 a = dl->parts * dl->nr;
1176                                 data = dl->verts;
1177                                 while (a--) {
1178                                         copy_v3_v3(mvert->co, data);
1179                                         data += 3;
1180                                         vertcount++;
1181                                         mvert++;
1182                                 }
1183
1184                                 for (a = 0; a < dl->parts; a++) {
1185                                         ofs = a * dl->nr;
1186                                         for (b = 0; b < dl->nr; b++) {
1187                                                 medge->v1 = startvert + ofs + b;
1188                                                 if (b == dl->nr - 1) medge->v2 = startvert + ofs;
1189                                                 else medge->v2 = startvert + ofs + b + 1;
1190                                                 medge->flag = ME_LOOSEEDGE | ME_EDGERENDER | ME_EDGEDRAW;
1191                                                 medge++;
1192                                         }
1193                                 }
1194                         }
1195                 }
1196                 else if (dl->type == DL_INDEX3) {
1197                         startvert = vertcount;
1198                         a = dl->nr;
1199                         data = dl->verts;
1200                         while (a--) {
1201                                 copy_v3_v3(mvert->co, data);
1202                                 data += 3;
1203                                 vertcount++;
1204                                 mvert++;
1205                         }
1206
1207                         a = dl->parts;
1208                         index = dl->index;
1209                         while (a--) {
1210                                 mloop[0].v = startvert + index[0];
1211                                 mloop[1].v = startvert + index[2];
1212                                 mloop[2].v = startvert + index[1];
1213                                 mpoly->loopstart = (int)(mloop - (*r_allloop));
1214                                 mpoly->totloop = 3;
1215                                 mpoly->mat_nr = dl->col;
1216
1217                                 if (mloopuv) {
1218                                         int i;
1219
1220                                         for (i = 0; i < 3; i++, mloopuv++) {
1221                                                 mloopuv->uv[0] = (mloop[i].v - startvert) / (float)(dl->nr - 1);
1222                                                 mloopuv->uv[1] = 0.0f;
1223                                         }
1224                                 }
1225
1226                                 if (is_smooth) mpoly->flag |= ME_SMOOTH;
1227                                 mpoly++;
1228                                 mloop += 3;
1229                                 index += 3;
1230                         }
1231                 }
1232                 else if (dl->type == DL_SURF) {
1233                         startvert = vertcount;
1234                         a = dl->parts * dl->nr;
1235                         data = dl->verts;
1236                         while (a--) {
1237                                 copy_v3_v3(mvert->co, data);
1238                                 data += 3;
1239                                 vertcount++;
1240                                 mvert++;
1241                         }
1242
1243                         for (a = 0; a < dl->parts; a++) {
1244
1245                                 if ( (dl->flag & DL_CYCL_V) == 0 && a == dl->parts - 1) break;
1246
1247                                 if (dl->flag & DL_CYCL_U) {         /* p2 -> p1 -> */
1248                                         p1 = startvert + dl->nr * a;    /* p4 -> p3 -> */
1249                                         p2 = p1 + dl->nr - 1;       /* -----> next row */
1250                                         p3 = p1 + dl->nr;
1251                                         p4 = p2 + dl->nr;
1252                                         b = 0;
1253                                 }
1254                                 else {
1255                                         p2 = startvert + dl->nr * a;
1256                                         p1 = p2 + 1;
1257                                         p4 = p2 + dl->nr;
1258                                         p3 = p1 + dl->nr;
1259                                         b = 1;
1260                                 }
1261                                 if ( (dl->flag & DL_CYCL_V) && a == dl->parts - 1) {
1262                                         p3 -= dl->parts * dl->nr;
1263                                         p4 -= dl->parts * dl->nr;
1264                                 }
1265
1266                                 for (; b < dl->nr; b++) {
1267                                         mloop[0].v = p1;
1268                                         mloop[1].v = p3;
1269                                         mloop[2].v = p4;
1270                                         mloop[3].v = p2;
1271                                         mpoly->loopstart = (int)(mloop - (*r_allloop));
1272                                         mpoly->totloop = 4;
1273                                         mpoly->mat_nr = dl->col;
1274
1275                                         if (mloopuv) {
1276                                                 int orco_sizeu = dl->nr - 1;
1277                                                 int orco_sizev = dl->parts - 1;
1278                                                 int i;
1279
1280                                                 /* exception as handled in convertblender.c too */
1281                                                 if (dl->flag & DL_CYCL_U) {
1282                                                         orco_sizeu++;
1283                                                         if (dl->flag & DL_CYCL_V)
1284                                                                 orco_sizev++;
1285                                                 }
1286                                                 else if (dl->flag & DL_CYCL_V) {
1287                                                         orco_sizev++;
1288                                                 }
1289
1290                                                 for (i = 0; i < 4; i++, mloopuv++) {
1291                                                         /* find uv based on vertex index into grid array */
1292                                                         int v = mloop[i].v - startvert;
1293
1294                                                         mloopuv->uv[0] = (v / dl->nr) / (float)orco_sizev;
1295                                                         mloopuv->uv[1] = (v % dl->nr) / (float)orco_sizeu;
1296
1297                                                         /* cyclic correction */
1298                                                         if ((i == 1 || i == 2) && mloopuv->uv[0] == 0.0f)
1299                                                                 mloopuv->uv[0] = 1.0f;
1300                                                         if ((i == 0 || i == 1) && mloopuv->uv[1] == 0.0f)
1301                                                                 mloopuv->uv[1] = 1.0f;
1302                                                 }
1303                                         }
1304
1305                                         if (is_smooth) mpoly->flag |= ME_SMOOTH;
1306                                         mpoly++;
1307                                         mloop += 4;
1308
1309                                         p4 = p3;
1310                                         p3++;
1311                                         p2 = p1;
1312                                         p1++;
1313                                 }
1314                         }
1315                 }
1316
1317                 dl = dl->next;
1318         }
1319         
1320         if (totvlak) {
1321                 make_edges_mdata_extend(r_alledge, &totedge,
1322                                         *r_allpoly, *r_allloop, totvlak);
1323         }
1324
1325         *r_totpoly = totvlak;
1326         *r_totloop = totloop;
1327         *r_totedge = totedge;
1328         *r_totvert = totvert;
1329
1330         return 0;
1331 }
1332
1333
1334 /* this may fail replacing ob->data, be sure to check ob->type */
1335 void BKE_mesh_from_nurbs_displist(Object *ob, ListBase *dispbase, const bool use_orco_uv)
1336 {
1337         Main *bmain = G.main;
1338         Object *ob1;
1339         DerivedMesh *dm = ob->derivedFinal;
1340         Mesh *me;
1341         Curve *cu;
1342         MVert *allvert = NULL;
1343         MEdge *alledge = NULL;
1344         MLoop *allloop = NULL;
1345         MLoopUV *alluv = NULL;
1346         MPoly *allpoly = NULL;
1347         int totvert, totedge, totloop, totpoly;
1348
1349         cu = ob->data;
1350
1351         if (dm == NULL) {
1352                 if (BKE_mesh_nurbs_displist_to_mdata(ob, dispbase, &allvert, &totvert,
1353                                                      &alledge, &totedge, &allloop,
1354                                                      &allpoly, (use_orco_uv) ? &alluv : NULL,
1355                                                      &totloop, &totpoly) != 0)
1356                 {
1357                         /* Error initializing */
1358                         return;
1359                 }
1360
1361                 /* make mesh */
1362                 me = BKE_mesh_add(G.main, "Mesh");
1363                 me->totvert = totvert;
1364                 me->totedge = totedge;
1365                 me->totloop = totloop;
1366                 me->totpoly = totpoly;
1367
1368                 me->mvert = CustomData_add_layer(&me->vdata, CD_MVERT, CD_ASSIGN, allvert, me->totvert);
1369                 me->medge = CustomData_add_layer(&me->edata, CD_MEDGE, CD_ASSIGN, alledge, me->totedge);
1370                 me->mloop = CustomData_add_layer(&me->ldata, CD_MLOOP, CD_ASSIGN, allloop, me->totloop);
1371                 me->mpoly = CustomData_add_layer(&me->pdata, CD_MPOLY, CD_ASSIGN, allpoly, me->totpoly);
1372
1373                 if (alluv) {
1374                         const char *uvname = "Orco";
1375                         me->mtpoly = CustomData_add_layer_named(&me->pdata, CD_MTEXPOLY, CD_DEFAULT, NULL, me->totpoly, uvname);
1376                         me->mloopuv = CustomData_add_layer_named(&me->ldata, CD_MLOOPUV, CD_ASSIGN, alluv, me->totloop, uvname);
1377                 }
1378
1379                 BKE_mesh_calc_normals(me);
1380         }
1381         else {
1382                 me = BKE_mesh_add(G.main, "Mesh");
1383                 DM_to_mesh(dm, me, ob, CD_MASK_MESH, false);
1384         }
1385
1386         me->totcol = cu->totcol;
1387         me->mat = cu->mat;
1388
1389         BKE_mesh_texspace_calc(me);
1390
1391         cu->mat = NULL;
1392         cu->totcol = 0;
1393
1394         if (ob->data) {
1395                 BKE_libblock_free(bmain, ob->data);
1396         }
1397         ob->data = me;
1398         ob->type = OB_MESH;
1399
1400         /* other users */
1401         ob1 = bmain->object.first;
1402         while (ob1) {
1403                 if (ob1->data == cu) {
1404                         ob1->type = OB_MESH;
1405                 
1406                         ob1->data = ob->data;
1407                         id_us_plus((ID *)ob->data);
1408                 }
1409                 ob1 = ob1->id.next;
1410         }
1411 }
1412
1413 void BKE_mesh_from_nurbs(Object *ob)
1414 {
1415         Curve *cu = (Curve *) ob->data;
1416         bool use_orco_uv = (cu->flag & CU_UV_ORCO) != 0;
1417         ListBase disp = {NULL, NULL};
1418
1419         if (ob->curve_cache) {
1420                 disp = ob->curve_cache->disp;
1421         }
1422
1423         BKE_mesh_from_nurbs_displist(ob, &disp, use_orco_uv);
1424 }
1425
1426 typedef struct EdgeLink {
1427         struct EdgeLink *next, *prev;
1428         void *edge;
1429 } EdgeLink;
1430
1431 typedef struct VertLink {
1432         Link *next, *prev;
1433         unsigned int index;
1434 } VertLink;
1435
1436 static void prependPolyLineVert(ListBase *lb, unsigned int index)
1437 {
1438         VertLink *vl = MEM_callocN(sizeof(VertLink), "VertLink");
1439         vl->index = index;
1440         BLI_addhead(lb, vl);
1441 }
1442
1443 static void appendPolyLineVert(ListBase *lb, unsigned int index)
1444 {
1445         VertLink *vl = MEM_callocN(sizeof(VertLink), "VertLink");
1446         vl->index = index;
1447         BLI_addtail(lb, vl);
1448 }
1449
1450 void BKE_mesh_to_curve_nurblist(DerivedMesh *dm, ListBase *nurblist, const int edge_users_test)
1451 {
1452         MVert       *mvert = dm->getVertArray(dm);
1453         MEdge *med, *medge = dm->getEdgeArray(dm);
1454         MPoly *mp,  *mpoly = dm->getPolyArray(dm);
1455         MLoop       *mloop = dm->getLoopArray(dm);
1456
1457         int dm_totedge = dm->getNumEdges(dm);
1458         int dm_totpoly = dm->getNumPolys(dm);
1459         int totedges = 0;
1460         int i;
1461
1462         /* only to detect edge polylines */
1463         int *edge_users;
1464
1465         ListBase edges = {NULL, NULL};
1466
1467         /* get boundary edges */
1468         edge_users = MEM_callocN(sizeof(int) * dm_totedge, __func__);
1469         for (i = 0, mp = mpoly; i < dm_totpoly; i++, mp++) {
1470                 MLoop *ml = &mloop[mp->loopstart];
1471                 int j;
1472                 for (j = 0; j < mp->totloop; j++, ml++) {
1473                         edge_users[ml->e]++;
1474                 }
1475         }
1476
1477         /* create edges from all faces (so as to find edges not in any faces) */
1478         med = medge;
1479         for (i = 0; i < dm_totedge; i++, med++) {
1480                 if (edge_users[i] == edge_users_test) {
1481                         EdgeLink *edl = MEM_callocN(sizeof(EdgeLink), "EdgeLink");
1482                         edl->edge = med;
1483
1484                         BLI_addtail(&edges, edl);   totedges++;
1485                 }
1486         }
1487         MEM_freeN(edge_users);
1488
1489         if (edges.first) {
1490                 while (edges.first) {
1491                         /* each iteration find a polyline and add this as a nurbs poly spline */
1492
1493                         ListBase polyline = {NULL, NULL}; /* store a list of VertLink's */
1494                         bool closed = false;
1495                         int totpoly = 0;
1496                         MEdge *med_current = ((EdgeLink *)edges.last)->edge;
1497                         unsigned int startVert = med_current->v1;
1498                         unsigned int endVert = med_current->v2;
1499                         bool ok = true;
1500
1501                         appendPolyLineVert(&polyline, startVert);   totpoly++;
1502                         appendPolyLineVert(&polyline, endVert);     totpoly++;
1503                         BLI_freelinkN(&edges, edges.last);          totedges--;
1504
1505                         while (ok) { /* while connected edges are found... */
1506                                 EdgeLink *edl = edges.last;
1507                                 ok = false;
1508                                 while (edl) {
1509                                         EdgeLink *edl_prev = edl->prev;
1510
1511                                         med = edl->edge;
1512
1513                                         if (med->v1 == endVert) {
1514                                                 endVert = med->v2;
1515                                                 appendPolyLineVert(&polyline, med->v2); totpoly++;
1516                                                 BLI_freelinkN(&edges, edl);             totedges--;
1517                                                 ok = true;
1518                                         }
1519                                         else if (med->v2 == endVert) {
1520                                                 endVert = med->v1;
1521                                                 appendPolyLineVert(&polyline, endVert); totpoly++;
1522                                                 BLI_freelinkN(&edges, edl);             totedges--;
1523                                                 ok = true;
1524                                         }
1525                                         else if (med->v1 == startVert) {
1526                                                 startVert = med->v2;
1527                                                 prependPolyLineVert(&polyline, startVert);  totpoly++;
1528                                                 BLI_freelinkN(&edges, edl);                 totedges--;
1529                                                 ok = true;
1530                                         }
1531                                         else if (med->v2 == startVert) {
1532                                                 startVert = med->v1;
1533                                                 prependPolyLineVert(&polyline, startVert);  totpoly++;
1534                                                 BLI_freelinkN(&edges, edl);                 totedges--;
1535                                                 ok = true;
1536                                         }
1537
1538                                         edl = edl_prev;
1539                                 }
1540                         }
1541
1542                         /* Now we have a polyline, make into a curve */
1543                         if (startVert == endVert) {
1544                                 BLI_freelinkN(&polyline, polyline.last);
1545                                 totpoly--;
1546                                 closed = true;
1547                         }
1548
1549                         /* --- nurbs --- */
1550                         {
1551                                 Nurb *nu;
1552                                 BPoint *bp;
1553                                 VertLink *vl;
1554
1555                                 /* create new 'nurb' within the curve */
1556                                 nu = (Nurb *)MEM_callocN(sizeof(Nurb), "MeshNurb");
1557
1558                                 nu->pntsu = totpoly;
1559                                 nu->pntsv = 1;
1560                                 nu->orderu = 4;
1561                                 nu->flagu = CU_NURB_ENDPOINT | (closed ? CU_NURB_CYCLIC : 0);  /* endpoint */
1562                                 nu->resolu = 12;
1563
1564                                 nu->bp = (BPoint *)MEM_callocN(sizeof(BPoint) * totpoly, "bpoints");
1565
1566                                 /* add points */
1567                                 vl = polyline.first;
1568                                 for (i = 0, bp = nu->bp; i < totpoly; i++, bp++, vl = (VertLink *)vl->next) {
1569                                         copy_v3_v3(bp->vec, mvert[vl->index].co);
1570                                         bp->f1 = SELECT;
1571                                         bp->radius = bp->weight = 1.0;
1572                                 }
1573                                 BLI_freelistN(&polyline);
1574
1575                                 /* add nurb to curve */
1576                                 BLI_addtail(nurblist, nu);
1577                         }
1578                         /* --- done with nurbs --- */
1579                 }
1580         }
1581 }
1582
1583 void BKE_mesh_to_curve(Scene *scene, Object *ob)
1584 {
1585         /* make new mesh data from the original copy */
1586         DerivedMesh *dm = mesh_get_derived_final(scene, ob, CD_MASK_MESH);
1587         ListBase nurblist = {NULL, NULL};
1588         bool needsFree = false;
1589
1590         BKE_mesh_to_curve_nurblist(dm, &nurblist, 0);
1591         BKE_mesh_to_curve_nurblist(dm, &nurblist, 1);
1592
1593         if (nurblist.first) {
1594                 Curve *cu = BKE_curve_add(G.main, ob->id.name + 2, OB_CURVE);
1595                 cu->flag |= CU_3D;
1596
1597                 cu->nurb = nurblist;
1598
1599                 id_us_min(&((Mesh *)ob->data)->id);
1600                 ob->data = cu;
1601                 ob->type = OB_CURVE;
1602
1603                 /* curve objects can't contain DM in usual cases, we could free memory */
1604                 needsFree = true;
1605         }
1606
1607         dm->needsFree = needsFree;
1608         dm->release(dm);
1609
1610         if (needsFree) {
1611                 ob->derivedFinal = NULL;
1612
1613                 /* curve object could have got bounding box only in special cases */
1614                 if (ob->bb) {
1615                         MEM_freeN(ob->bb);
1616                         ob->bb = NULL;
1617                 }
1618         }
1619 }
1620
1621 void BKE_mesh_material_index_remove(Mesh *me, short index)
1622 {
1623         MPoly *mp;
1624         MFace *mf;
1625         int i;
1626
1627         for (mp = me->mpoly, i = 0; i < me->totpoly; i++, mp++) {
1628                 if (mp->mat_nr && mp->mat_nr >= index) {
1629                         mp->mat_nr--;
1630                 }
1631         }
1632
1633         for (mf = me->mface, i = 0; i < me->totface; i++, mf++) {
1634                 if (mf->mat_nr && mf->mat_nr >= index) {
1635                         mf->mat_nr--;
1636                 }
1637         }
1638 }
1639
1640 void BKE_mesh_material_index_clear(Mesh *me)
1641 {
1642         MPoly *mp;
1643         MFace *mf;
1644         int i;
1645
1646         for (mp = me->mpoly, i = 0; i < me->totpoly; i++, mp++) {
1647                 mp->mat_nr = 0;
1648         }
1649
1650         for (mf = me->mface, i = 0; i < me->totface; i++, mf++) {
1651                 mf->mat_nr = 0;
1652         }
1653 }
1654
1655 void BKE_mesh_material_remap(Mesh *me, const unsigned int *remap, unsigned int remap_len)
1656 {
1657         const short remap_len_short = (short)remap_len;
1658
1659 #define MAT_NR_REMAP(n) \
1660         if (n < remap_len_short) { \
1661                 BLI_assert(n >= 0 && remap[n] < remap_len_short); \
1662                 n = remap[n]; \
1663         } ((void)0)
1664
1665         if (me->edit_btmesh) {
1666                 BMEditMesh *em = me->edit_btmesh;
1667                 BMIter iter;
1668                 BMFace *efa;
1669
1670                 BM_ITER_MESH(efa, &iter, em->bm, BM_FACES_OF_MESH) {
1671                         MAT_NR_REMAP(efa->mat_nr);
1672                 }
1673         }
1674         else {
1675                 int i;
1676                 for (i = 0; i < me->totpoly; i++) {
1677                         MAT_NR_REMAP(me->mpoly[i].mat_nr);
1678                 }
1679         }
1680
1681 #undef MAT_NR_REMAP
1682
1683 }
1684
1685 void BKE_mesh_smooth_flag_set(Object *meshOb, int enableSmooth) 
1686 {
1687         Mesh *me = meshOb->data;
1688         int i;
1689
1690         for (i = 0; i < me->totpoly; i++) {
1691                 MPoly *mp = &me->mpoly[i];
1692
1693                 if (enableSmooth) {
1694                         mp->flag |= ME_SMOOTH;
1695                 }
1696                 else {
1697                         mp->flag &= ~ME_SMOOTH;
1698                 }
1699         }
1700         
1701         for (i = 0; i < me->totface; i++) {
1702                 MFace *mf = &me->mface[i];
1703
1704                 if (enableSmooth) {
1705                         mf->flag |= ME_SMOOTH;
1706                 }
1707                 else {
1708                         mf->flag &= ~ME_SMOOTH;
1709                 }
1710         }
1711 }
1712
1713 /**
1714  * Return a newly MEM_malloc'd array of all the mesh vertex locations
1715  * \note \a r_numVerts may be NULL
1716  */
1717 float (*BKE_mesh_vertexCos_get(const Mesh *me, int *r_numVerts))[3]
1718 {
1719         int i, numVerts = me->totvert;
1720         float (*cos)[3] = MEM_mallocN(sizeof(*cos) * numVerts, "vertexcos1");
1721
1722         if (r_numVerts) *r_numVerts = numVerts;
1723         for (i = 0; i < numVerts; i++)
1724                 copy_v3_v3(cos[i], me->mvert[i].co);
1725
1726         return cos;
1727 }
1728
1729 /**
1730  * Find the index of the loop in 'poly' which references vertex,
1731  * returns -1 if not found
1732  */
1733 int poly_find_loop_from_vert(
1734         const MPoly *poly, const MLoop *loopstart,
1735         unsigned vert)
1736 {
1737         int j;
1738         for (j = 0; j < poly->totloop; j++, loopstart++) {
1739                 if (loopstart->v == vert)
1740                         return j;
1741         }
1742         
1743         return -1;
1744 }
1745
1746 /**
1747  * Fill \a r_adj with the loop indices in \a poly adjacent to the
1748  * vertex. Returns the index of the loop matching vertex, or -1 if the
1749  * vertex is not in \a poly
1750  */
1751 int poly_get_adj_loops_from_vert(
1752         const MPoly *poly,
1753         const MLoop *mloop, unsigned int vert,
1754         unsigned int r_adj[2])
1755 {
1756         int corner = poly_find_loop_from_vert(poly,
1757                                               &mloop[poly->loopstart],
1758                                               vert);
1759                 
1760         if (corner != -1) {
1761 #if 0   /* unused - this loop */
1762                 const MLoop *ml = &mloop[poly->loopstart + corner];
1763 #endif
1764
1765                 /* vertex was found */
1766                 r_adj[0] = ME_POLY_LOOP_PREV(mloop, poly, corner)->v;
1767                 r_adj[1] = ME_POLY_LOOP_NEXT(mloop, poly, corner)->v;
1768         }
1769
1770         return corner;
1771 }
1772
1773 /**
1774  * Return the index of the edge vert that is not equal to \a v. If
1775  * neither edge vertex is equal to \a v, returns -1.
1776  */
1777 int BKE_mesh_edge_other_vert(const MEdge *e, int v)
1778 {
1779         if (e->v1 == v)
1780                 return e->v2;
1781         else if (e->v2 == v)
1782                 return e->v1;
1783         else
1784                 return -1;
1785 }
1786
1787 /* basic vertex data functions */
1788 bool BKE_mesh_minmax(const Mesh *me, float r_min[3], float r_max[3])
1789 {
1790         int i = me->totvert;
1791         MVert *mvert;
1792         for (mvert = me->mvert; i--; mvert++) {
1793                 minmax_v3v3_v3(r_min, r_max, mvert->co);
1794         }
1795         
1796         return (me->totvert != 0);
1797 }
1798
1799 void BKE_mesh_transform(Mesh *me, float mat[4][4], bool do_keys)
1800 {
1801         int i;
1802         MVert *mvert = me->mvert;
1803         float (*lnors)[3] = CustomData_get_layer(&me->ldata, CD_NORMAL);
1804
1805         for (i = 0; i < me->totvert; i++, mvert++)
1806                 mul_m4_v3(mat, mvert->co);
1807
1808         if (do_keys && me->key) {
1809                 KeyBlock *kb;
1810                 for (kb = me->key->block.first; kb; kb = kb->next) {
1811                         float *fp = kb->data;
1812                         for (i = kb->totelem; i--; fp += 3) {
1813                                 mul_m4_v3(mat, fp);
1814                         }
1815                 }
1816         }
1817
1818         /* don't update normals, caller can do this explicitly.
1819          * We do update loop normals though, those may not be auto-generated (see e.g. STL import script)! */
1820         if (lnors) {
1821                 float m3[3][3];
1822
1823                 copy_m3_m4(m3, mat);
1824                 normalize_m3(m3);
1825                 for (i = 0; i < me->totloop; i++, lnors++) {
1826                         mul_m3_v3(m3, *lnors);
1827                 }
1828         }
1829 }
1830
1831 void BKE_mesh_translate(Mesh *me, const float offset[3], const bool do_keys)
1832 {
1833         int i = me->totvert;
1834         MVert *mvert;
1835         for (mvert = me->mvert; i--; mvert++) {
1836                 add_v3_v3(mvert->co, offset);
1837         }
1838         
1839         if (do_keys && me->key) {
1840                 KeyBlock *kb;
1841                 for (kb = me->key->block.first; kb; kb = kb->next) {
1842                         float *fp = kb->data;
1843                         for (i = kb->totelem; i--; fp += 3) {
1844                                 add_v3_v3(fp, offset);
1845                         }
1846                 }
1847         }
1848 }
1849
1850 void BKE_mesh_ensure_navmesh(Mesh *me)
1851 {
1852         if (!CustomData_has_layer(&me->pdata, CD_RECAST)) {
1853                 int i;
1854                 int numFaces = me->totpoly;
1855                 int *recastData;
1856                 recastData = (int *)MEM_mallocN(numFaces * sizeof(int), __func__);
1857                 for (i = 0; i < numFaces; i++) {
1858                         recastData[i] = i + 1;
1859                 }
1860                 CustomData_add_layer_named(&me->pdata, CD_RECAST, CD_ASSIGN, recastData, numFaces, "recastData");
1861         }
1862 }
1863
1864 void BKE_mesh_tessface_calc(Mesh *mesh)
1865 {
1866         mesh->totface = BKE_mesh_recalc_tessellation(&mesh->fdata, &mesh->ldata, &mesh->pdata,
1867                                                      mesh->mvert,
1868                                                      mesh->totface, mesh->totloop, mesh->totpoly,
1869                                                      /* calc normals right after, don't copy from polys here */
1870                                                      false);
1871
1872         BKE_mesh_update_customdata_pointers(mesh, true);
1873 }
1874
1875 void BKE_mesh_tessface_ensure(Mesh *mesh)
1876 {
1877         if (mesh->totpoly && mesh->totface == 0) {
1878                 BKE_mesh_tessface_calc(mesh);
1879         }
1880 }
1881
1882 void BKE_mesh_tessface_clear(Mesh *mesh)
1883 {
1884         mesh_tessface_clear_intern(mesh, true);
1885 }
1886
1887 void BKE_mesh_do_versions_cd_flag_init(Mesh *mesh)
1888 {
1889         if (UNLIKELY(mesh->cd_flag)) {
1890                 return;
1891         }
1892         else {
1893                 MVert *mv;
1894                 MEdge *med;
1895                 int i;
1896
1897                 for (mv = mesh->mvert, i = 0; i < mesh->totvert; mv++, i++) {
1898                         if (mv->bweight != 0) {
1899                                 mesh->cd_flag |= ME_CDFLAG_VERT_BWEIGHT;
1900                                 break;
1901                         }
1902                 }
1903
1904                 for (med = mesh->medge, i = 0; i < mesh->totedge; med++, i++) {
1905                         if (med->bweight != 0) {
1906                                 mesh->cd_flag |= ME_CDFLAG_EDGE_BWEIGHT;
1907                                 if (mesh->cd_flag & ME_CDFLAG_EDGE_CREASE) {
1908                                         break;
1909                                 }
1910                         }
1911                         if (med->crease != 0) {
1912                                 mesh->cd_flag |= ME_CDFLAG_EDGE_CREASE;
1913                                 if (mesh->cd_flag & ME_CDFLAG_EDGE_BWEIGHT) {
1914                                         break;
1915                                 }
1916                         }
1917                 }
1918
1919         }
1920 }
1921
1922
1923 /* -------------------------------------------------------------------- */
1924 /* MSelect functions (currently used in weight paint mode) */
1925
1926 void BKE_mesh_mselect_clear(Mesh *me)
1927 {
1928         if (me->mselect) {
1929                 MEM_freeN(me->mselect);
1930                 me->mselect = NULL;
1931         }
1932         me->totselect = 0;
1933 }
1934
1935 void BKE_mesh_mselect_validate(Mesh *me)
1936 {
1937         MSelect *mselect_src, *mselect_dst;
1938         int i_src, i_dst;
1939
1940         if (me->totselect == 0)
1941                 return;
1942
1943         mselect_src = me->mselect;
1944         mselect_dst = MEM_mallocN(sizeof(MSelect) * (me->totselect), "Mesh selection history");
1945
1946         for (i_src = 0, i_dst = 0; i_src < me->totselect; i_src++) {
1947                 int index = mselect_src[i_src].index;
1948                 switch (mselect_src[i_src].type) {
1949                         case ME_VSEL:
1950                         {
1951                                 if (me->mvert[index].flag & SELECT) {
1952                                         mselect_dst[i_dst] = mselect_src[i_src];
1953                                         i_dst++;
1954                                 }
1955                                 break;
1956                         }
1957                         case ME_ESEL:
1958                         {
1959                                 if (me->medge[index].flag & SELECT) {
1960                                         mselect_dst[i_dst] = mselect_src[i_src];
1961                                         i_dst++;
1962                                 }
1963                                 break;
1964                         }
1965                         case ME_FSEL:
1966                         {
1967                                 if (me->mpoly[index].flag & SELECT) {
1968                                         mselect_dst[i_dst] = mselect_src[i_src];
1969                                         i_dst++;
1970                                 }
1971                                 break;
1972                         }
1973                         default:
1974                         {
1975                                 BLI_assert(0);
1976                                 break;
1977                         }
1978                 }
1979         }
1980
1981         MEM_freeN(mselect_src);
1982
1983         if (i_dst == 0) {
1984                 MEM_freeN(mselect_dst);
1985                 mselect_dst = NULL;
1986         }
1987         else if (i_dst != me->totselect) {
1988                 mselect_dst = MEM_reallocN(mselect_dst, sizeof(MSelect) * i_dst);
1989         }
1990
1991         me->totselect = i_dst;
1992         me->mselect = mselect_dst;
1993
1994 }
1995
1996 /**
1997  * Return the index within me->mselect, or -1
1998  */
1999 int BKE_mesh_mselect_find(Mesh *me, int index, int type)
2000 {
2001         int i;
2002
2003         BLI_assert(ELEM(type, ME_VSEL, ME_ESEL, ME_FSEL));
2004
2005         for (i = 0; i < me->totselect; i++) {
2006                 if ((me->mselect[i].index == index) &&
2007                     (me->mselect[i].type == type))
2008                 {
2009                         return i;
2010                 }
2011         }
2012
2013         return -1;
2014 }
2015
2016 /**
2017  * Return The index of the active element.
2018  */
2019 int BKE_mesh_mselect_active_get(Mesh *me, int type)
2020 {
2021         BLI_assert(ELEM(type, ME_VSEL, ME_ESEL, ME_FSEL));
2022
2023         if (me->totselect) {
2024                 if (me->mselect[me->totselect - 1].type == type) {
2025                         return me->mselect[me->totselect - 1].index;
2026                 }
2027         }
2028         return -1;
2029 }
2030
2031 void BKE_mesh_mselect_active_set(Mesh *me, int index, int type)
2032 {
2033         const int msel_index = BKE_mesh_mselect_find(me, index, type);
2034
2035         if (msel_index == -1) {
2036                 /* add to the end */
2037                 me->mselect = MEM_reallocN(me->mselect, sizeof(MSelect) * (me->totselect + 1));
2038                 me->mselect[me->totselect].index = index;
2039                 me->mselect[me->totselect].type  = type;
2040                 me->totselect++;
2041         }
2042         else if (msel_index != me->totselect - 1) {
2043                 /* move to the end */
2044                 SWAP(MSelect, me->mselect[msel_index], me->mselect[me->totselect - 1]);
2045         }
2046
2047         BLI_assert((me->mselect[me->totselect - 1].index == index) &&
2048                    (me->mselect[me->totselect - 1].type  == type));
2049 }
2050
2051 void BKE_mesh_calc_normals_split(Mesh *mesh)
2052 {
2053         float (*r_loopnors)[3];
2054         float (*polynors)[3];
2055         short (*clnors)[2] = NULL;
2056         bool free_polynors = false;
2057
2058         if (CustomData_has_layer(&mesh->ldata, CD_NORMAL)) {
2059                 r_loopnors = CustomData_get_layer(&mesh->ldata, CD_NORMAL);
2060                 memset(r_loopnors, 0, sizeof(float[3]) * mesh->totloop);
2061         }
2062         else {
2063                 r_loopnors = CustomData_add_layer(&mesh->ldata, CD_NORMAL, CD_CALLOC, NULL, mesh->totloop);
2064                 CustomData_set_layer_flag(&mesh->ldata, CD_NORMAL, CD_FLAG_TEMPORARY);
2065         }
2066
2067         /* may be NULL */
2068         clnors = CustomData_get_layer(&mesh->ldata, CD_CUSTOMLOOPNORMAL);
2069
2070         if (CustomData_has_layer(&mesh->pdata, CD_NORMAL)) {
2071                 /* This assume that layer is always up to date, not sure this is the case (esp. in Edit mode?)... */
2072                 polynors = CustomData_get_layer(&mesh->pdata, CD_NORMAL);
2073                 free_polynors = false;
2074         }
2075         else {
2076                 polynors = MEM_mallocN(sizeof(float[3]) * mesh->totpoly, __func__);
2077                 BKE_mesh_calc_normals_poly(
2078                             mesh->mvert, NULL, mesh->totvert,
2079                             mesh->mloop, mesh->mpoly, mesh->totloop, mesh->totpoly, polynors, false);
2080                 free_polynors = true;
2081         }
2082
2083         BKE_mesh_normals_loop_split(
2084                 mesh->mvert, mesh->totvert, mesh->medge, mesh->totedge,
2085                 mesh->mloop, r_loopnors, mesh->totloop, mesh->mpoly, (const float (*)[3])polynors, mesh->totpoly,
2086                 (mesh->flag & ME_AUTOSMOOTH) != 0, mesh->smoothresh, NULL, clnors, NULL);
2087
2088         if (free_polynors) {
2089                 MEM_freeN(polynors);
2090         }
2091 }
2092
2093 /* Spli faces based on the edge angle.
2094  * Matches behavior of face splitting in render engines.
2095  */
2096 void BKE_mesh_split_faces(Mesh *mesh)
2097 {
2098         const int num_verts = mesh->totvert;
2099         const int num_edges = mesh->totedge;
2100         const int num_polys = mesh->totpoly;
2101         MVert *mvert = mesh->mvert;
2102         MEdge *medge = mesh->medge;
2103         MLoop *mloop = mesh->mloop;
2104         MPoly *mpoly = mesh->mpoly;
2105         float (*lnors)[3];
2106         int poly, num_new_verts = 0;
2107         if ((mesh->flag & ME_AUTOSMOOTH) == 0) {
2108                 return;
2109         }
2110         BKE_mesh_tessface_clear(mesh);
2111         /* Compute loop normals if needed. */
2112         if (!CustomData_has_layer(&mesh->ldata, CD_NORMAL)) {
2113                 BKE_mesh_calc_normals_split(mesh);
2114         }
2115         lnors = CustomData_get_layer(&mesh->ldata, CD_NORMAL);
2116         /* Count number of vertices to be split. */
2117         for (poly = 0; poly < num_polys; poly++) {
2118                 MPoly *mp = &mpoly[poly];
2119                 int loop;
2120                 for (loop = 0; loop < mp->totloop; loop++) {
2121                         MLoop *ml = &mloop[mp->loopstart + loop];
2122                         MVert *mv = &mvert[ml->v];
2123                         float vn[3];
2124                         normal_short_to_float_v3(vn, mv->no);
2125                         if (!equals_v3v3(vn, lnors[mp->loopstart + loop])) {
2126                                 num_new_verts++;
2127                         }
2128                 }
2129         }
2130         if (num_new_verts == 0) {
2131                 /* No new vertices are to be added, can do early exit. */
2132                 return;
2133         }
2134         /* Reallocate all vert and edge related data. */
2135         mesh->totvert += num_new_verts;
2136         mesh->totedge += 2 * num_new_verts;
2137         CustomData_realloc(&mesh->vdata, mesh->totvert);
2138         CustomData_realloc(&mesh->edata, mesh->totedge);
2139         /* Update pointers to a newly allocated memory. */
2140         BKE_mesh_update_customdata_pointers(mesh, false);
2141         mvert = mesh->mvert;
2142         medge = mesh->medge;
2143         /* Perform actual vertex split. */
2144         num_new_verts = 0;
2145         for (poly = 0; poly < num_polys; poly++) {
2146                 MPoly *mp = &mpoly[poly];
2147                 int loop;
2148                 for (loop = 0; loop < mp->totloop; loop++) {
2149                         int poly_loop = mp->loopstart + loop;
2150                         MLoop *ml = &mloop[poly_loop];
2151                         MVert *mv = &mvert[ml->v];
2152                         float vn[3];
2153                         normal_short_to_float_v3(vn, mv->no);
2154                         if (!equals_v3v3(vn, lnors[mp->loopstart + loop])) {
2155                                 int poly_loop_prev = mp->loopstart + (loop + mp->totloop - 1) % mp->totloop;
2156                                 MLoop *ml_prev = &mloop[poly_loop_prev];
2157                                 int new_edge_prev, new_edge;
2158                                 /* Cretae new vertex. */
2159                                 int new_vert = num_verts + num_new_verts;
2160                                 CustomData_copy_data(&mesh->vdata, &mesh->vdata,
2161                                                      ml->v, new_vert, 1);
2162                                 normal_float_to_short_v3(mvert[new_vert].no,
2163                                                          lnors[poly_loop]);
2164                                 /* Create new edges. */
2165                                 new_edge_prev = num_edges + 2 * num_new_verts;
2166                                 new_edge = num_edges + 2 * num_new_verts + 1;
2167                                 CustomData_copy_data(&mesh->edata, &mesh->edata,
2168                                                      ml_prev->e, new_edge_prev, 1);
2169                                 CustomData_copy_data(&mesh->edata, &mesh->edata,
2170                                                      ml->e, new_edge, 1);
2171                                 if (medge[new_edge_prev].v1 == ml->v) {
2172                                         medge[new_edge_prev].v1 = new_vert;
2173                                 }
2174                                 else {
2175                                         medge[new_edge_prev].v2 = new_vert;
2176                                 }
2177                                 if (medge[new_edge].v1 == ml->v) {
2178                                         medge[new_edge].v1 = new_vert;
2179                                 }
2180                                 else {
2181                                         medge[new_edge].v2 = new_vert;
2182                                 }
2183
2184                                 ml->v = new_vert;
2185                                 ml_prev->e = new_edge_prev;
2186                                 ml->e = new_edge;
2187                                 num_new_verts++;
2188                         }
2189                 }
2190         }
2191 }
2192
2193 /* settings: 1 - preview, 2 - render */
2194 Mesh *BKE_mesh_new_from_object(
2195         Main *bmain, Scene *sce, Object *ob,
2196         int apply_modifiers, int settings, int calc_tessface, int calc_undeformed)
2197 {
2198         Mesh *tmpmesh;
2199         Curve *tmpcu = NULL, *copycu;
2200         int i;
2201         const bool render = (settings == eModifierMode_Render);
2202         const bool cage = !apply_modifiers;
2203         bool do_mat_id_us = true;
2204
2205         /* perform the mesh extraction based on type */
2206         switch (ob->type) {
2207                 case OB_FONT:
2208                 case OB_CURVE:
2209                 case OB_SURF:
2210                 {
2211                         ListBase dispbase = {NULL, NULL};
2212                         DerivedMesh *derivedFinal = NULL;
2213                         int uv_from_orco;
2214
2215                         /* copies object and modifiers (but not the data) */
2216                         Object *tmpobj = BKE_object_copy_ex(bmain, ob, true);
2217                         tmpcu = (Curve *)tmpobj->data;
2218                         id_us_min(&tmpcu->id);
2219
2220                         /* Copy cached display list, it might be needed by the stack evaluation.
2221                          * Ideally stack should be able to use render-time display list, but doing
2222                          * so is quite tricky and not safe so close to the release.
2223                          *
2224                          * TODO(sergey): Look into more proper solution.
2225                          */
2226                         if (ob->curve_cache != NULL) {
2227                                 if (tmpobj->curve_cache == NULL) {
2228                                         tmpobj->curve_cache = MEM_callocN(sizeof(CurveCache), "CurveCache for curve types");
2229                                 }
2230                                 BKE_displist_copy(&tmpobj->curve_cache->disp, &ob->curve_cache->disp);
2231                         }
2232
2233                         /* if getting the original caged mesh, delete object modifiers */
2234                         if (cage)
2235                                 BKE_object_free_modifiers(tmpobj);
2236
2237                         /* copies the data */
2238                         copycu = tmpobj->data = BKE_curve_copy(bmain, (Curve *) ob->data);
2239
2240                         /* temporarily set edit so we get updates from edit mode, but
2241                          * also because for text datablocks copying it while in edit
2242                          * mode gives invalid data structures */
2243                         copycu->editfont = tmpcu->editfont;
2244                         copycu->editnurb = tmpcu->editnurb;
2245
2246                         /* get updated display list, and convert to a mesh */
2247                         BKE_displist_make_curveTypes_forRender(sce, tmpobj, &dispbase, &derivedFinal, false, render);
2248
2249                         copycu->editfont = NULL;
2250                         copycu->editnurb = NULL;
2251
2252                         tmpobj->derivedFinal = derivedFinal;
2253
2254                         /* convert object type to mesh */
2255                         uv_from_orco = (tmpcu->flag & CU_UV_ORCO) != 0;
2256                         BKE_mesh_from_nurbs_displist(tmpobj, &dispbase, uv_from_orco);
2257
2258                         tmpmesh = tmpobj->data;
2259
2260                         BKE_displist_free(&dispbase);
2261
2262                         /* BKE_mesh_from_nurbs changes the type to a mesh, check it worked.
2263                          * if it didn't the curve did not have any segments or otherwise 
2264                          * would have generated an empty mesh */
2265                         if (tmpobj->type != OB_MESH) {
2266                                 BKE_libblock_free_us(bmain, tmpobj);
2267                                 return NULL;
2268                         }
2269
2270                         BKE_mesh_texspace_copy_from_object(tmpmesh, ob);
2271
2272                         BKE_libblock_free_us(bmain, tmpobj);
2273
2274                         /* XXX The curve to mesh conversion is convoluted... But essentially, BKE_mesh_from_nurbs_displist()
2275                          *     already transfers the ownership of materials from the temp copy of the Curve ID to the new
2276                          *     Mesh ID, so we do not want to increase materials' usercount later. */
2277                         do_mat_id_us = false;
2278
2279                         break;
2280                 }
2281
2282                 case OB_MBALL:
2283                 {
2284                         /* metaballs don't have modifiers, so just convert to mesh */
2285                         Object *basis_ob = BKE_mball_basis_find(sce, ob);
2286                         /* todo, re-generatre for render-res */
2287                         /* metaball_polygonize(scene, ob) */
2288
2289                         if (ob != basis_ob)
2290                                 return NULL;  /* only do basis metaball */
2291
2292                         tmpmesh = BKE_mesh_add(bmain, "Mesh");
2293                         /* BKE_mesh_add gives us a user count we don't need */
2294                         id_us_min(&tmpmesh->id);
2295
2296                         if (render) {
2297                                 ListBase disp = {NULL, NULL};
2298                                 /* TODO(sergey): This is gonna to work for until EvaluationContext
2299                                  *               only contains for_render flag. As soon as CoW is
2300                                  *               implemented, this is to be rethinked.
2301                                  */
2302                                 EvaluationContext eval_ctx;
2303                                 DEG_evaluation_context_init(&eval_ctx, DAG_EVAL_RENDER);
2304                                 BKE_displist_make_mball_forRender(&eval_ctx, sce, ob, &disp);
2305                                 BKE_mesh_from_metaball(&disp, tmpmesh);
2306                                 BKE_displist_free(&disp);
2307                         }
2308                         else {
2309                                 ListBase disp = {NULL, NULL};
2310                                 if (ob->curve_cache) {
2311                                         disp = ob->curve_cache->disp;
2312                                 }
2313                                 BKE_mesh_from_metaball(&disp, tmpmesh);
2314                         }
2315
2316                         BKE_mesh_texspace_copy_from_object(tmpmesh, ob);
2317
2318                         break;
2319
2320                 }
2321                 case OB_MESH:
2322                         /* copies object and modifiers (but not the data) */
2323                         if (cage) {
2324                                 /* copies the data */
2325                                 tmpmesh = BKE_mesh_copy(bmain, ob->data);
2326
2327                                 /* XXX BKE_mesh_copy() already handles materials usercount. */
2328                                 do_mat_id_us = false;
2329                         }
2330                         /* if not getting the original caged mesh, get final derived mesh */
2331                         else {
2332                                 /* Make a dummy mesh, saves copying */
2333                                 DerivedMesh *dm;
2334                                 /* CustomDataMask mask = CD_MASK_BAREMESH|CD_MASK_MTFACE|CD_MASK_MCOL; */
2335                                 CustomDataMask mask = CD_MASK_MESH; /* this seems more suitable, exporter,
2336                                                                  * for example, needs CD_MASK_MDEFORMVERT */
2337
2338                                 if (calc_undeformed)
2339                                         mask |= CD_MASK_ORCO;
2340
2341                                 /* Write the display mesh into the dummy mesh */
2342                                 if (render)
2343                                         dm = mesh_create_derived_render(sce, ob, mask);
2344                                 else
2345                                         dm = mesh_create_derived_view(sce, ob, mask);
2346
2347                                 tmpmesh = BKE_mesh_add(bmain, "Mesh");
2348                                 DM_to_mesh(dm, tmpmesh, ob, mask, true);
2349                         }
2350
2351                         /* BKE_mesh_add/copy gives us a user count we don't need */
2352                         id_us_min(&tmpmesh->id);
2353
2354                         break;
2355                 default:
2356                         /* "Object does not have geometry data") */
2357                         return NULL;
2358         }
2359
2360         /* Copy materials to new mesh */
2361         switch (ob->type) {
2362                 case OB_SURF:
2363                 case OB_FONT:
2364                 case OB_CURVE:
2365                         tmpmesh->totcol = tmpcu->totcol;
2366
2367                         /* free old material list (if it exists) and adjust user counts */
2368                         if (tmpcu->mat) {
2369                                 for (i = tmpcu->totcol; i-- > 0; ) {
2370                                         /* are we an object material or data based? */
2371                                         if (ob->matbits[i] && i >= ob->totcol) {
2372                                                 tmpmesh->mat[i] = NULL;
2373                                         }
2374                                         else {
2375                                                 tmpmesh->mat[i] = ob->matbits[i] ? ob->mat[i] : tmpcu->mat[i];
2376                                         }
2377
2378                                         if (do_mat_id_us && tmpmesh->mat[i]) {
2379                                                 id_us_plus(&tmpmesh->mat[i]->id);
2380                                         }
2381                                 }
2382                         }
2383                         break;
2384
2385                 case OB_MBALL:
2386                 {
2387                         MetaBall *tmpmb = (MetaBall *)ob->data;
2388                         tmpmesh->mat = MEM_dupallocN(tmpmb->mat);
2389                         tmpmesh->totcol = tmpmb->totcol;
2390
2391                         /* free old material list (if it exists) and adjust user counts */
2392                         if (tmpmb->mat) {
2393                                 for (i = tmpmb->totcol; i-- > 0; ) {
2394                                         /* are we an object material or data based? */
2395                                         if (ob->matbits[i] && i >= ob->totcol) {
2396                                                 tmpmesh->mat[i] = NULL;
2397                                         }
2398                                         else {
2399                                                 tmpmesh->mat[i] = ob->matbits[i] ? ob->mat[i] : tmpmb->mat[i];
2400                                         }
2401
2402                                         if (do_mat_id_us && tmpmesh->mat[i]) {
2403                                                 id_us_plus(&tmpmesh->mat[i]->id);
2404                                         }
2405                                 }
2406                         }
2407                         break;
2408                 }
2409
2410                 case OB_MESH:
2411                         if (!cage) {
2412                                 Mesh *origmesh = ob->data;
2413                                 tmpmesh->flag = origmesh->flag;
2414                                 tmpmesh->mat = MEM_dupallocN(origmesh->mat);
2415                                 tmpmesh->totcol = origmesh->totcol;
2416                                 tmpmesh->smoothresh = origmesh->smoothresh;
2417                                 if (origmesh->mat) {
2418                                         for (i = origmesh->totcol; i-- > 0; ) {
2419                                                 /* are we an object material or data based? */
2420                                                 if (ob->matbits[i] && i >= ob->totcol) {
2421                                                         tmpmesh->mat[i] = NULL;
2422                                                 }
2423                                                 else {
2424                                                         tmpmesh->mat[i] = ob->matbits[i] ? ob->mat[i] : origmesh->mat[i];
2425                                                 }
2426
2427                                                 if (do_mat_id_us && tmpmesh->mat[i]) {
2428                                                         id_us_plus(&tmpmesh->mat[i]->id);
2429                                                 }
2430                                         }
2431                                 }
2432                         }
2433                         break;
2434         } /* end copy materials */
2435
2436         if (calc_tessface) {
2437                 /* cycles and exporters rely on this still */
2438                 BKE_mesh_tessface_ensure(tmpmesh);
2439         }
2440
2441         return tmpmesh;
2442 }
2443
2444 /* **** Depsgraph evaluation **** */
2445
2446 void BKE_mesh_eval_geometry(EvaluationContext *UNUSED(eval_ctx),
2447                             Mesh *mesh)
2448 {
2449         if (G.debug & G_DEBUG_DEPSGRAPH) {
2450                 printf("%s on %s\n", __func__, mesh->id.name);
2451         }
2452         if (mesh->bb == NULL || (mesh->bb->flag & BOUNDBOX_DIRTY)) {
2453                 BKE_mesh_texspace_calc(mesh);
2454         }
2455 }