Add material slot reorder buttons
[blender.git] / source / blender / blenkernel / intern / mesh.c
1 /*
2  * ***** BEGIN GPL LICENSE BLOCK *****
3  *
4  * This program is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU General Public License
6  * as published by the Free Software Foundation; either version 2
7  * of the License, or (at your option) any later version.
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with this program; if not, write to the Free Software Foundation,
16  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
17  *
18  * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
19  * All rights reserved.
20  *
21  * Contributor(s): Blender Foundation
22  *
23  * ***** END GPL LICENSE BLOCK *****
24  */
25
26 /** \file blender/blenkernel/intern/mesh.c
27  *  \ingroup bke
28  */
29
30 #include "MEM_guardedalloc.h"
31
32 #include "DNA_scene_types.h"
33 #include "DNA_material_types.h"
34 #include "DNA_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
1924         for (i = 0; i < me->totvert; i++, mvert++)
1925                 mul_m4_v3(mat, mvert->co);
1926
1927         if (do_keys && me->key) {
1928                 KeyBlock *kb;
1929                 for (kb = me->key->block.first; kb; kb = kb->next) {
1930                         float *fp = kb->data;
1931                         for (i = kb->totelem; i--; fp += 3) {
1932                                 mul_m4_v3(mat, fp);
1933                         }
1934                 }
1935         }
1936
1937         /* don't update normals, caller can do this explicitly */
1938 }
1939
1940 void BKE_mesh_translate(Mesh *me, const float offset[3], const bool do_keys)
1941 {
1942         int i = me->totvert;
1943         MVert *mvert;
1944         for (mvert = me->mvert; i--; mvert++) {
1945                 add_v3_v3(mvert->co, offset);
1946         }
1947         
1948         if (do_keys && me->key) {
1949                 KeyBlock *kb;
1950                 for (kb = me->key->block.first; kb; kb = kb->next) {
1951                         float *fp = kb->data;
1952                         for (i = kb->totelem; i--; fp += 3) {
1953                                 add_v3_v3(fp, offset);
1954                         }
1955                 }
1956         }
1957 }
1958
1959 void BKE_mesh_ensure_navmesh(Mesh *me)
1960 {
1961         if (!CustomData_has_layer(&me->pdata, CD_RECAST)) {
1962                 int i;
1963                 int numFaces = me->totpoly;
1964                 int *recastData;
1965                 recastData = (int *)MEM_mallocN(numFaces * sizeof(int), __func__);
1966                 for (i = 0; i < numFaces; i++) {
1967                         recastData[i] = i + 1;
1968                 }
1969                 CustomData_add_layer_named(&me->pdata, CD_RECAST, CD_ASSIGN, recastData, numFaces, "recastData");
1970         }
1971 }
1972
1973 void BKE_mesh_tessface_calc(Mesh *mesh)
1974 {
1975         mesh->totface = BKE_mesh_recalc_tessellation(&mesh->fdata, &mesh->ldata, &mesh->pdata,
1976                                                      mesh->mvert,
1977                                                      mesh->totface, mesh->totloop, mesh->totpoly,
1978                                                      /* calc normals right after, don't copy from polys here */
1979                                                      false);
1980
1981         BKE_mesh_update_customdata_pointers(mesh, true);
1982 }
1983
1984 void BKE_mesh_tessface_ensure(Mesh *mesh)
1985 {
1986         if (mesh->totpoly && mesh->totface == 0) {
1987                 BKE_mesh_tessface_calc(mesh);
1988         }
1989 }
1990
1991 void BKE_mesh_tessface_clear(Mesh *mesh)
1992 {
1993         mesh_tessface_clear_intern(mesh, true);
1994 }
1995
1996 void BKE_mesh_do_versions_cd_flag_init(Mesh *mesh)
1997 {
1998         if (UNLIKELY(mesh->cd_flag)) {
1999                 return;
2000         }
2001         else {
2002                 MVert *mv;
2003                 MEdge *med;
2004                 int i;
2005
2006                 for (mv = mesh->mvert, i = 0; i < mesh->totvert; mv++, i++) {
2007                         if (mv->bweight != 0) {
2008                                 mesh->cd_flag |= ME_CDFLAG_VERT_BWEIGHT;
2009                                 break;
2010                         }
2011                 }
2012
2013                 for (med = mesh->medge, i = 0; i < mesh->totedge; med++, i++) {
2014                         if (med->bweight != 0) {
2015                                 mesh->cd_flag |= ME_CDFLAG_EDGE_BWEIGHT;
2016                                 if (mesh->cd_flag & ME_CDFLAG_EDGE_CREASE) {
2017                                         break;
2018                                 }
2019                         }
2020                         if (med->crease != 0) {
2021                                 mesh->cd_flag |= ME_CDFLAG_EDGE_CREASE;
2022                                 if (mesh->cd_flag & ME_CDFLAG_EDGE_BWEIGHT) {
2023                                         break;
2024                                 }
2025                         }
2026                 }
2027
2028         }
2029 }
2030
2031
2032 /* -------------------------------------------------------------------- */
2033 /* MSelect functions (currently used in weight paint mode) */
2034
2035 void BKE_mesh_mselect_clear(Mesh *me)
2036 {
2037         if (me->mselect) {
2038                 MEM_freeN(me->mselect);
2039                 me->mselect = NULL;
2040         }
2041         me->totselect = 0;
2042 }
2043
2044 void BKE_mesh_mselect_validate(Mesh *me)
2045 {
2046         MSelect *mselect_src, *mselect_dst;
2047         int i_src, i_dst;
2048
2049         if (me->totselect == 0)
2050                 return;
2051
2052         mselect_src = me->mselect;
2053         mselect_dst = MEM_mallocN(sizeof(MSelect) * (me->totselect), "Mesh selection history");
2054
2055         for (i_src = 0, i_dst = 0; i_src < me->totselect; i_src++) {
2056                 int index = mselect_src[i_src].index;
2057                 switch (mselect_src[i_src].type) {
2058                         case ME_VSEL:
2059                         {
2060                                 if (me->mvert[index].flag & SELECT) {
2061                                         mselect_dst[i_dst] = mselect_src[i_src];
2062                                         i_dst++;
2063                                 }
2064                                 break;
2065                         }
2066                         case ME_ESEL:
2067                         {
2068                                 if (me->medge[index].flag & SELECT) {
2069                                         mselect_dst[i_dst] = mselect_src[i_src];
2070                                         i_dst++;
2071                                 }
2072                                 break;
2073                         }
2074                         case ME_FSEL:
2075                         {
2076                                 if (me->mpoly[index].flag & SELECT) {
2077                                         mselect_dst[i_dst] = mselect_src[i_src];
2078                                         i_dst++;
2079                                 }
2080                                 break;
2081                         }
2082                         default:
2083                         {
2084                                 BLI_assert(0);
2085                                 break;
2086                         }
2087                 }
2088         }
2089
2090         MEM_freeN(mselect_src);
2091
2092         if (i_dst == 0) {
2093                 MEM_freeN(mselect_dst);
2094                 mselect_dst = NULL;
2095         }
2096         else if (i_dst != me->totselect) {
2097                 mselect_dst = MEM_reallocN(mselect_dst, sizeof(MSelect) * i_dst);
2098         }
2099
2100         me->totselect = i_dst;
2101         me->mselect = mselect_dst;
2102
2103 }
2104
2105 /**
2106  * Return the index within me->mselect, or -1
2107  */
2108 int BKE_mesh_mselect_find(Mesh *me, int index, int type)
2109 {
2110         int i;
2111
2112         BLI_assert(ELEM(type, ME_VSEL, ME_ESEL, ME_FSEL));
2113
2114         for (i = 0; i < me->totselect; i++) {
2115                 if ((me->mselect[i].index == index) &&
2116                     (me->mselect[i].type == type))
2117                 {
2118                         return i;
2119                 }
2120         }
2121
2122         return -1;
2123 }
2124
2125 /**
2126  * Return The index of the active element.
2127  */
2128 int BKE_mesh_mselect_active_get(Mesh *me, int type)
2129 {
2130         BLI_assert(ELEM(type, ME_VSEL, ME_ESEL, ME_FSEL));
2131
2132         if (me->totselect) {
2133                 if (me->mselect[me->totselect - 1].type == type) {
2134                         return me->mselect[me->totselect - 1].index;
2135                 }
2136         }
2137         return -1;
2138 }
2139
2140 void BKE_mesh_mselect_active_set(Mesh *me, int index, int type)
2141 {
2142         const int msel_index = BKE_mesh_mselect_find(me, index, type);
2143
2144         if (msel_index == -1) {
2145                 /* add to the end */
2146                 me->mselect = MEM_reallocN(me->mselect, sizeof(MSelect) * (me->totselect + 1));
2147                 me->mselect[me->totselect].index = index;
2148                 me->mselect[me->totselect].type  = type;
2149                 me->totselect++;
2150         }
2151         else if (msel_index != me->totselect - 1) {
2152                 /* move to the end */
2153                 SWAP(MSelect, me->mselect[msel_index], me->mselect[me->totselect - 1]);
2154         }
2155
2156         BLI_assert((me->mselect[me->totselect - 1].index == index) &&
2157                    (me->mselect[me->totselect - 1].type  == type));
2158 }
2159
2160 void BKE_mesh_calc_normals_split(Mesh *mesh)
2161 {
2162         float (*r_loopnors)[3];
2163         float (*polynors)[3];
2164         short (*clnors)[2] = NULL;
2165         bool free_polynors = false;
2166
2167         if (CustomData_has_layer(&mesh->ldata, CD_NORMAL)) {
2168                 r_loopnors = CustomData_get_layer(&mesh->ldata, CD_NORMAL);
2169                 memset(r_loopnors, 0, sizeof(float[3]) * mesh->totloop);
2170         }
2171         else {
2172                 r_loopnors = CustomData_add_layer(&mesh->ldata, CD_NORMAL, CD_CALLOC, NULL, mesh->totloop);
2173                 CustomData_set_layer_flag(&mesh->ldata, CD_NORMAL, CD_FLAG_TEMPORARY);
2174         }
2175
2176         /* may be NULL */
2177         clnors = CustomData_get_layer(&mesh->ldata, CD_CUSTOMLOOPNORMAL);
2178
2179         if (CustomData_has_layer(&mesh->pdata, CD_NORMAL)) {
2180                 /* This assume that layer is always up to date, not sure this is the case (esp. in Edit mode?)... */
2181                 polynors = CustomData_get_layer(&mesh->pdata, CD_NORMAL);
2182                 free_polynors = false;
2183         }
2184         else {
2185                 polynors = MEM_mallocN(sizeof(float[3]) * mesh->totpoly, __func__);
2186                 BKE_mesh_calc_normals_poly(mesh->mvert, mesh->totvert, mesh->mloop, mesh->mpoly, mesh->totloop, mesh->totpoly,
2187                                            polynors, false);
2188                 free_polynors = true;
2189         }
2190
2191         BKE_mesh_normals_loop_split(
2192                 mesh->mvert, mesh->totvert, mesh->medge, mesh->totedge,
2193                 mesh->mloop, r_loopnors, mesh->totloop, mesh->mpoly, (const float (*)[3])polynors, mesh->totpoly,
2194                 (mesh->flag & ME_AUTOSMOOTH) != 0, mesh->smoothresh, NULL, clnors, NULL);
2195
2196         if (free_polynors) {
2197                 MEM_freeN(polynors);
2198         }
2199 }
2200
2201 /* Spli faces based on the edge angle.
2202  * Matches behavior of face splitting in render engines.
2203  */
2204 void BKE_mesh_split_faces(Mesh *mesh)
2205 {
2206         const int num_verts = mesh->totvert;
2207         const int num_edges = mesh->totedge;
2208         const int num_polys = mesh->totpoly;
2209         MVert *mvert = mesh->mvert;
2210         MEdge *medge = mesh->medge;
2211         MLoop *mloop = mesh->mloop;
2212         MPoly *mpoly = mesh->mpoly;
2213         float (*lnors)[3];
2214         int poly, num_new_verts = 0;
2215         if ((mesh->flag & ME_AUTOSMOOTH) == 0) {
2216                 return;
2217         }
2218         BKE_mesh_tessface_clear(mesh);
2219         /* Compute loop normals if needed. */
2220         if (!CustomData_has_layer(&mesh->ldata, CD_NORMAL)) {
2221                 BKE_mesh_calc_normals_split(mesh);
2222         }
2223         lnors = CustomData_get_layer(&mesh->ldata, CD_NORMAL);
2224         /* Count. */
2225         for (poly = 0; poly < num_polys; poly++) {
2226                 MPoly *mp = &mpoly[poly];
2227                 int loop;
2228                 for (loop = 0; loop < mp->totloop; loop++) {
2229                         MLoop *ml = &mloop[mp->loopstart + loop];
2230                         MVert *mv = &mvert[ml->v];
2231                         float vn[3];
2232                         normal_short_to_float_v3(vn, mv->no);
2233                         if (!equals_v3v3(vn, lnors[mp->loopstart + loop])) {
2234                                 num_new_verts++;
2235                         }
2236                 }
2237         }
2238         if (num_new_verts == 0) {
2239                 /* No new vertices are to be added, can do early exit. */
2240                 return;
2241         }
2242         /* Actual split. */
2243         mesh->totvert += num_new_verts;
2244         mesh->totedge += 2 * num_new_verts;
2245         mvert = mesh->mvert = MEM_reallocN(mesh->mvert,
2246                                            sizeof(MVert) * mesh->totvert);
2247         medge = mesh->medge = MEM_reallocN(mesh->medge,
2248                                            sizeof(MEdge) * mesh->totedge);
2249         CustomData_set_layer(&mesh->vdata, CD_MVERT, mesh->mvert);
2250         CustomData_set_layer(&mesh->edata, CD_MEDGE, mesh->medge);
2251         num_new_verts = 0;
2252         for (poly = 0; poly < num_polys; poly++) {
2253                 MPoly *mp = &mpoly[poly];
2254                 int loop;
2255                 for (loop = 0; loop < mp->totloop; loop++) {
2256                         int poly_loop = mp->loopstart + loop;
2257                         MLoop *ml = &mloop[poly_loop];
2258                         MVert *mv = &mvert[ml->v];
2259                         float vn[3];
2260                         normal_short_to_float_v3(vn, mv->no);
2261                         if (!equals_v3v3(vn, lnors[mp->loopstart + loop])) {
2262                                 int poly_loop_prev = mp->loopstart + (loop + mp->totloop - 1) % mp->totloop;
2263                                 MLoop *ml_prev = &mloop[poly_loop_prev];
2264                                 int new_edge_prev, new_edge;
2265                                 /* Cretae new vertex. */
2266                                 int new_vert = num_verts + num_new_verts;
2267                                 CustomData_copy_data(&mesh->vdata, &mesh->vdata,
2268                                                      ml->v, new_vert, 1);
2269                                 normal_float_to_short_v3(mvert[new_vert].no,
2270                                                          lnors[poly_loop]);
2271                                 /* Create new edges. */
2272                                 new_edge_prev = num_edges + 2 * num_new_verts;
2273                                 new_edge = num_edges + 2 * num_new_verts + 1;
2274                                 CustomData_copy_data(&mesh->edata, &mesh->edata,
2275                                                      ml_prev->e, new_edge_prev, 1);
2276                                 CustomData_copy_data(&mesh->edata, &mesh->edata,
2277                                                      ml->e, new_edge, 1);
2278                                 if (medge[new_edge_prev].v1 == ml->v) {
2279                                         medge[new_edge_prev].v1 = new_vert;
2280                                 }
2281                                 else {
2282                                         medge[new_edge_prev].v2 = new_vert;
2283                                 }
2284                                 if (medge[new_edge].v1 == ml->v) {
2285                                         medge[new_edge].v1 = new_vert;
2286                                 }
2287                                 else {
2288                                         medge[new_edge].v2 = new_vert;
2289                                 }
2290
2291                                 ml->v = new_vert;
2292                                 ml_prev->e = new_edge_prev;
2293                                 ml->e = new_edge;
2294                                 num_new_verts++;
2295                         }
2296                 }
2297         }
2298 }
2299
2300 /* settings: 1 - preview, 2 - render */
2301 Mesh *BKE_mesh_new_from_object(
2302         Main *bmain, Scene *sce, Object *ob,
2303         int apply_modifiers, int settings, int calc_tessface, int calc_undeformed)
2304 {
2305         Mesh *tmpmesh;
2306         Curve *tmpcu = NULL, *copycu;
2307         Object *tmpobj = NULL;
2308         int render = settings == eModifierMode_Render, i;
2309         int cage = !apply_modifiers;
2310
2311         /* perform the mesh extraction based on type */
2312         switch (ob->type) {
2313                 case OB_FONT:
2314                 case OB_CURVE:
2315                 case OB_SURF:
2316                 {
2317                         ListBase dispbase = {NULL, NULL};
2318                         DerivedMesh *derivedFinal = NULL;
2319                         int uv_from_orco;
2320
2321                         /* copies object and modifiers (but not the data) */
2322                         tmpobj = BKE_object_copy_ex(bmain, ob, true);
2323                         tmpcu = (Curve *)tmpobj->data;
2324                         tmpcu->id.us--;
2325
2326                         /* if getting the original caged mesh, delete object modifiers */
2327                         if (cage)
2328                                 BKE_object_free_modifiers(tmpobj);
2329
2330                         /* copies the data */
2331                         copycu = tmpobj->data = BKE_curve_copy((Curve *) ob->data);
2332
2333                         /* temporarily set edit so we get updates from edit mode, but
2334                          * also because for text datablocks copying it while in edit
2335                          * mode gives invalid data structures */
2336                         copycu->editfont = tmpcu->editfont;
2337                         copycu->editnurb = tmpcu->editnurb;
2338
2339                         /* get updated display list, and convert to a mesh */
2340                         BKE_displist_make_curveTypes_forRender(sce, tmpobj, &dispbase, &derivedFinal, false, render);
2341
2342                         copycu->editfont = NULL;
2343                         copycu->editnurb = NULL;
2344
2345                         tmpobj->derivedFinal = derivedFinal;
2346
2347                         /* convert object type to mesh */
2348                         uv_from_orco = (tmpcu->flag & CU_UV_ORCO) != 0;
2349                         BKE_mesh_from_nurbs_displist(tmpobj, &dispbase, uv_from_orco);
2350
2351                         tmpmesh = tmpobj->data;
2352
2353                         BKE_displist_free(&dispbase);
2354
2355                         /* BKE_mesh_from_nurbs changes the type to a mesh, check it worked.
2356                          * if it didn't the curve did not have any segments or otherwise 
2357                          * would have generated an empty mesh */
2358                         if (tmpobj->type != OB_MESH) {
2359                                 BKE_libblock_free_us(bmain, tmpobj);
2360                                 return NULL;
2361                         }
2362
2363                         BKE_mesh_texspace_copy_from_object(tmpmesh, ob);
2364
2365                         BKE_libblock_free_us(bmain, tmpobj);
2366                         break;
2367                 }
2368
2369                 case OB_MBALL:
2370                 {
2371                         /* metaballs don't have modifiers, so just convert to mesh */
2372                         Object *basis_ob = BKE_mball_basis_find(sce, ob);
2373                         /* todo, re-generatre for render-res */
2374                         /* metaball_polygonize(scene, ob) */
2375
2376                         if (ob != basis_ob)
2377                                 return NULL;  /* only do basis metaball */
2378
2379                         tmpmesh = BKE_mesh_add(bmain, "Mesh");
2380                         /* BKE_mesh_add gives us a user count we don't need */
2381                         tmpmesh->id.us--;
2382
2383                         if (render) {
2384                                 ListBase disp = {NULL, NULL};
2385                                 /* TODO(sergey): This is gonna to work for until EvaluationContext
2386                                  *               only contains for_render flag. As soon as CoW is
2387                                  *               implemented, this is to be rethinked.
2388                                  */
2389                                 EvaluationContext eval_ctx = {0};
2390                                 eval_ctx.mode = DAG_EVAL_RENDER;
2391                                 BKE_displist_make_mball_forRender(&eval_ctx, sce, ob, &disp);
2392                                 BKE_mesh_from_metaball(&disp, tmpmesh);
2393                                 BKE_displist_free(&disp);
2394                         }
2395                         else {
2396                                 ListBase disp = {NULL, NULL};
2397                                 if (ob->curve_cache) {
2398                                         disp = ob->curve_cache->disp;
2399                                 }
2400                                 BKE_mesh_from_metaball(&disp, tmpmesh);
2401                         }
2402
2403                         BKE_mesh_texspace_copy_from_object(tmpmesh, ob);
2404
2405                         break;
2406
2407                 }
2408                 case OB_MESH:
2409                         /* copies object and modifiers (but not the data) */
2410                         if (cage) {
2411                                 /* copies the data */
2412                                 tmpmesh = BKE_mesh_copy_ex(bmain, ob->data);
2413                                 /* if not getting the original caged mesh, get final derived mesh */
2414                         }
2415                         else {
2416                                 /* Make a dummy mesh, saves copying */
2417                                 DerivedMesh *dm;
2418                                 /* CustomDataMask mask = CD_MASK_BAREMESH|CD_MASK_MTFACE|CD_MASK_MCOL; */
2419                                 CustomDataMask mask = CD_MASK_MESH; /* this seems more suitable, exporter,
2420                                                                  * for example, needs CD_MASK_MDEFORMVERT */
2421
2422                                 if (calc_undeformed)
2423                                         mask |= CD_MASK_ORCO;
2424
2425                                 /* Write the display mesh into the dummy mesh */
2426                                 if (render)
2427                                         dm = mesh_create_derived_render(sce, ob, mask);
2428                                 else
2429                                         dm = mesh_create_derived_view(sce, ob, mask);
2430
2431                                 tmpmesh = BKE_mesh_add(bmain, "Mesh");
2432                                 DM_to_mesh(dm, tmpmesh, ob, mask, true);
2433                         }
2434
2435                         /* BKE_mesh_add/copy gives us a user count we don't need */
2436                         tmpmesh->id.us--;
2437
2438                         break;
2439                 default:
2440                         /* "Object does not have geometry data") */
2441                         return NULL;
2442         }
2443
2444         /* Copy materials to new mesh */
2445         switch (ob->type) {
2446                 case OB_SURF:
2447                 case OB_FONT:
2448                 case OB_CURVE:
2449                         tmpmesh->totcol = tmpcu->totcol;
2450
2451                         /* free old material list (if it exists) and adjust user counts */
2452                         if (tmpcu->mat) {
2453                                 for (i = tmpcu->totcol; i-- > 0; ) {
2454                                         /* are we an object material or data based? */
2455
2456                                         tmpmesh->mat[i] = ob->matbits[i] ? ob->mat[i] : tmpcu->mat[i];
2457
2458                                         if (tmpmesh->mat[i]) {
2459                                                 tmpmesh->mat[i]->id.us++;
2460                                         }
2461                                 }
2462                         }
2463                         break;
2464
2465 #if 0
2466                 /* Crashes when assigning the new material, not sure why */
2467                 case OB_MBALL:
2468                         tmpmb = (MetaBall *)ob->data;
2469                         tmpmesh->totcol = tmpmb->totcol;
2470
2471                         /* free old material list (if it exists) and adjust user counts */
2472                         if (tmpmb->mat) {
2473                                 for (i = tmpmb->totcol; i-- > 0; ) {
2474                                         tmpmesh->mat[i] = tmpmb->mat[i]; /* CRASH HERE ??? */
2475                                         if (tmpmesh->mat[i]) {
2476                                                 tmpmb->mat[i]->id.us++;
2477                                         }
2478                                 }
2479                         }
2480                         break;
2481 #endif
2482
2483                 case OB_MESH:
2484                         if (!cage) {
2485                                 Mesh *origmesh = ob->data;
2486                                 tmpmesh->flag = origmesh->flag;
2487                                 tmpmesh->mat = MEM_dupallocN(origmesh->mat);
2488                                 tmpmesh->totcol = origmesh->totcol;
2489                                 tmpmesh->smoothresh = origmesh->smoothresh;
2490                                 if (origmesh->mat) {
2491                                         for (i = origmesh->totcol; i-- > 0; ) {
2492                                                 /* are we an object material or data based? */
2493                                                 tmpmesh->mat[i] = ob->matbits[i] ? ob->mat[i] : origmesh->mat[i];
2494
2495                                                 if (tmpmesh->mat[i]) {
2496                                                         tmpmesh->mat[i]->id.us++;
2497                                                 }
2498                                         }
2499                                 }
2500                         }
2501                         break;
2502         } /* end copy materials */
2503
2504         if (calc_tessface) {
2505                 /* cycles and exporters rely on this still */
2506                 BKE_mesh_tessface_ensure(tmpmesh);
2507         }
2508
2509         /* make sure materials get updated in objects */
2510         test_object_materials(bmain, &tmpmesh->id);
2511
2512         return tmpmesh;
2513 }
2514