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