copy BLI_edgehash changes from bmesh branch, main change is use of mempool.
[blender-staging.git] / source / blender / blenkernel / intern / customdata.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) 2006 Blender Foundation.
19  * All rights reserved.
20  *
21  * The Original Code is: all of this file.
22  *
23  * Contributor(s): Ben Batt <benbatt@gmail.com>
24  *
25  * ***** END GPL LICENSE BLOCK *****
26  *
27  * Implementation of CustomData.
28  *
29  * BKE_customdata.h contains the function prototypes for this file.
30  *
31  */
32
33 /** \file blender/blenkernel/intern/customdata.c
34  *  \ingroup bke
35  */
36  
37
38 #include <math.h>
39 #include <string.h>
40 #include <assert.h>
41
42 #include "MEM_guardedalloc.h"
43
44 #include "DNA_meshdata_types.h"
45 #include "DNA_ID.h"
46
47 #include "BLI_blenlib.h"
48 #include "BLI_linklist.h"
49 #include "BLI_math.h"
50 #include "BLI_mempool.h"
51 #include "BLI_utildefines.h"
52
53 #include "BKE_customdata.h"
54 #include "BKE_customdata_file.h"
55 #include "BKE_global.h"
56 #include "BKE_main.h"
57 #include "BKE_utildefines.h"
58 #include "BKE_multires.h"
59
60 /* number of layers to add when growing a CustomData object */
61 #define CUSTOMDATA_GROW 5
62
63 /********************* Layer type information **********************/
64 typedef struct LayerTypeInfo {
65         int size;          /* the memory size of one element of this layer's data */
66         const char *structname;  /* name of the struct used, for file writing */
67         int structnum;     /* number of structs per element, for file writing */
68         const char *defaultname; /* default layer name */
69
70         /* a function to copy count elements of this layer's data
71          * (deep copy if appropriate)
72          * if NULL, memcpy is used
73          */
74         void (*copy)(const void *source, void *dest, int count);
75
76         /* a function to free any dynamically allocated components of this
77          * layer's data (note the data pointer itself should not be freed)
78          * size should be the size of one element of this layer's data (e.g.
79          * LayerTypeInfo.size)
80          */
81         void (*free)(void *data, int count, int size);
82
83         /* a function to interpolate between count source elements of this
84          * layer's data and store the result in dest
85          * if weights == NULL or sub_weights == NULL, they should default to 1
86          *
87          * weights gives the weight for each element in sources
88          * sub_weights gives the sub-element weights for each element in sources
89          *    (there should be (sub element count)^2 weights per element)
90          * count gives the number of elements in sources
91          */
92         void (*interp)(void **sources, float *weights, float *sub_weights,
93                        int count, void *dest);
94
95         /* a function to swap the data in corners of the element */
96         void (*swap)(void *data, const int *corner_indices);
97
98         /* a function to set a layer's data to default values. if NULL, the
99            default is assumed to be all zeros */
100         void (*set_default)(void *data, int count);
101
102         /* a function to read data from a cdf file */
103         int (*read)(CDataFile *cdf, void *data, int count);
104
105         /* a function to write data to a cdf file */
106         int (*write)(CDataFile *cdf, void *data, int count);
107
108         /* a function to determine file size */
109         size_t (*filesize)(CDataFile *cdf, void *data, int count);
110
111         /* a function to validate layer contents depending on
112          * sub-elements count
113          */
114         void (*validate)(void *source, int sub_elements);
115 } LayerTypeInfo;
116
117 static void layerCopy_mdeformvert(const void *source, void *dest,
118                                                                   int count)
119 {
120         int i, size = sizeof(MDeformVert);
121
122         memcpy(dest, source, count * size);
123
124         for(i = 0; i < count; ++i) {
125                 MDeformVert *dvert = (MDeformVert *)((char *)dest + i * size);
126
127                 if(dvert->totweight) {
128                         MDeformWeight *dw = MEM_callocN(dvert->totweight * sizeof(*dw),
129                                                                                         "layerCopy_mdeformvert dw");
130
131                         memcpy(dw, dvert->dw, dvert->totweight * sizeof(*dw));
132                         dvert->dw = dw;
133                 }
134                 else
135                         dvert->dw = NULL;
136         }
137 }
138
139 static void layerFree_mdeformvert(void *data, int count, int size)
140 {
141         int i;
142
143         for(i = 0; i < count; ++i) {
144                 MDeformVert *dvert = (MDeformVert *)((char *)data + i * size);
145
146                 if(dvert->dw) {
147                         MEM_freeN(dvert->dw);
148                         dvert->dw = NULL;
149                         dvert->totweight = 0;
150                 }
151         }
152 }
153
154 static void linklist_free_simple(void *link)
155 {
156         MEM_freeN(link);
157 }
158
159 static void layerInterp_mdeformvert(void **sources, float *weights,
160                                                                         float *UNUSED(sub_weights), int count, void *dest)
161 {
162         MDeformVert *dvert = dest;
163         LinkNode *dest_dw = NULL; /* a list of lists of MDeformWeight pointers */
164         LinkNode *node;
165         int i, j, totweight;
166
167         if(count <= 0) return;
168
169         /* build a list of unique def_nrs for dest */
170         totweight = 0;
171         for(i = 0; i < count; ++i) {
172                 MDeformVert *source = sources[i];
173                 float interp_weight = weights ? weights[i] : 1.0f;
174
175                 for(j = 0; j < source->totweight; ++j) {
176                         MDeformWeight *dw = &source->dw[j];
177
178                         for(node = dest_dw; node; node = node->next) {
179                                 MDeformWeight *tmp_dw = (MDeformWeight *)node->link;
180
181                                 if(tmp_dw->def_nr == dw->def_nr) {
182                                         tmp_dw->weight += dw->weight * interp_weight;
183                                         break;
184                                 }
185                         }
186
187                         /* if this def_nr is not in the list, add it */
188                         if(!node) {
189                                 MDeformWeight *tmp_dw = MEM_callocN(sizeof(*tmp_dw),
190                                                                                         "layerInterp_mdeformvert tmp_dw");
191                                 tmp_dw->def_nr = dw->def_nr;
192                                 tmp_dw->weight = dw->weight * interp_weight;
193                                 BLI_linklist_prepend(&dest_dw, tmp_dw);
194                                 totweight++;
195                         }
196                 }
197         }
198
199         /* now we know how many unique deform weights there are, so realloc */
200         if(dvert->dw) MEM_freeN(dvert->dw);
201
202         if(totweight) {
203                 dvert->dw = MEM_callocN(sizeof(*dvert->dw) * totweight,
204                                                                 "layerInterp_mdeformvert dvert->dw");
205                 dvert->totweight = totweight;
206
207                 for(i = 0, node = dest_dw; node; node = node->next, ++i)
208                         dvert->dw[i] = *((MDeformWeight *)node->link);
209         }
210         else
211                 memset(dvert, 0, sizeof(*dvert));
212
213         BLI_linklist_free(dest_dw, linklist_free_simple);
214 }
215
216
217 static void layerInterp_msticky(void **sources, float *weights,
218                                                                 float *UNUSED(sub_weights), int count, void *dest)
219 {
220         float co[2], w;
221         MSticky *mst;
222         int i;
223
224         co[0] = co[1] = 0.0f;
225         for(i = 0; i < count; i++) {
226                 w = weights ? weights[i] : 1.0f;
227                 mst = (MSticky*)sources[i];
228
229                 co[0] += w*mst->co[0];
230                 co[1] += w*mst->co[1];
231         }
232
233         mst = (MSticky*)dest;
234         mst->co[0] = co[0];
235         mst->co[1] = co[1];
236 }
237
238
239 static void layerCopy_tface(const void *source, void *dest, int count)
240 {
241         const MTFace *source_tf = (const MTFace*)source;
242         MTFace *dest_tf = (MTFace*)dest;
243         int i;
244
245         for(i = 0; i < count; ++i)
246                 dest_tf[i] = source_tf[i];
247 }
248
249 static void layerInterp_tface(void **sources, float *weights,
250                                                           float *sub_weights, int count, void *dest)
251 {
252         MTFace *tf = dest;
253         int i, j, k;
254         float uv[4][2];
255         float *sub_weight;
256
257         if(count <= 0) return;
258
259         memset(uv, 0, sizeof(uv));
260
261         sub_weight = sub_weights;
262         for(i = 0; i < count; ++i) {
263                 float weight = weights ? weights[i] : 1;
264                 MTFace *src = sources[i];
265
266                 for(j = 0; j < 4; ++j) {
267                         if(sub_weights) {
268                                 for(k = 0; k < 4; ++k, ++sub_weight) {
269                                         float w = (*sub_weight) * weight;
270                                         float *tmp_uv = src->uv[k];
271
272                                         uv[j][0] += tmp_uv[0] * w;
273                                         uv[j][1] += tmp_uv[1] * w;
274                                 }
275                         } else {
276                                 uv[j][0] += src->uv[j][0] * weight;
277                                 uv[j][1] += src->uv[j][1] * weight;
278                         }
279                 }
280         }
281
282         *tf = *(MTFace *)sources[0];
283         for(j = 0; j < 4; ++j) {
284                 tf->uv[j][0] = uv[j][0];
285                 tf->uv[j][1] = uv[j][1];
286         }
287 }
288
289 static void layerSwap_tface(void *data, const int *corner_indices)
290 {
291         MTFace *tf = data;
292         float uv[4][2];
293         static const short pin_flags[4] =
294                 { TF_PIN1, TF_PIN2, TF_PIN3, TF_PIN4 };
295         static const char sel_flags[4] =
296                 { TF_SEL1, TF_SEL2, TF_SEL3, TF_SEL4 };
297         short unwrap = tf->unwrap & ~(TF_PIN1 | TF_PIN2 | TF_PIN3 | TF_PIN4);
298         char flag = tf->flag & ~(TF_SEL1 | TF_SEL2 | TF_SEL3 | TF_SEL4);
299         int j;
300
301         for(j = 0; j < 4; ++j) {
302                 int source_index = corner_indices[j];
303
304                 uv[j][0] = tf->uv[source_index][0];
305                 uv[j][1] = tf->uv[source_index][1];
306
307                 // swap pinning flags around
308                 if(tf->unwrap & pin_flags[source_index]) {
309                         unwrap |= pin_flags[j];
310                 }
311
312                 // swap selection flags around
313                 if(tf->flag & sel_flags[source_index]) {
314                         flag |= sel_flags[j];
315                 }
316         }
317
318         memcpy(tf->uv, uv, sizeof(tf->uv));
319         tf->unwrap = unwrap;
320         tf->flag = flag;
321 }
322
323 static void layerDefault_tface(void *data, int count)
324 {
325         static MTFace default_tf = {{{0, 0}, {1, 0}, {1, 1}, {0, 1}}, NULL,
326                                                            0, 0, TF_DYNAMIC|TF_CONVERTED, 0, 0};
327         MTFace *tf = (MTFace*)data;
328         int i;
329
330         for(i = 0; i < count; i++)
331                 tf[i] = default_tf;
332 }
333
334 static void layerCopy_origspace_face(const void *source, void *dest, int count)
335 {
336         const OrigSpaceFace *source_tf = (const OrigSpaceFace*)source;
337         OrigSpaceFace *dest_tf = (OrigSpaceFace*)dest;
338         int i;
339
340         for(i = 0; i < count; ++i)
341                 dest_tf[i] = source_tf[i];
342 }
343
344 static void layerInterp_origspace_face(void **sources, float *weights,
345                                                           float *sub_weights, int count, void *dest)
346 {
347         OrigSpaceFace *osf = dest;
348         int i, j, k;
349         float uv[4][2];
350         float *sub_weight;
351
352         if(count <= 0) return;
353
354         memset(uv, 0, sizeof(uv));
355
356         sub_weight = sub_weights;
357         for(i = 0; i < count; ++i) {
358                 float weight = weights ? weights[i] : 1;
359                 OrigSpaceFace *src = sources[i];
360
361                 for(j = 0; j < 4; ++j) {
362                         if(sub_weights) {
363                                 for(k = 0; k < 4; ++k, ++sub_weight) {
364                                         float w = (*sub_weight) * weight;
365                                         float *tmp_uv = src->uv[k];
366
367                                         uv[j][0] += tmp_uv[0] * w;
368                                         uv[j][1] += tmp_uv[1] * w;
369                                 }
370                         } else {
371                                 uv[j][0] += src->uv[j][0] * weight;
372                                 uv[j][1] += src->uv[j][1] * weight;
373                         }
374                 }
375         }
376
377         *osf = *(OrigSpaceFace *)sources[0];
378         for(j = 0; j < 4; ++j) {
379                 osf->uv[j][0] = uv[j][0];
380                 osf->uv[j][1] = uv[j][1];
381         }
382 }
383
384 static void layerSwap_origspace_face(void *data, const int *corner_indices)
385 {
386         OrigSpaceFace *osf = data;
387         float uv[4][2];
388         int j;
389
390         for(j = 0; j < 4; ++j) {
391                 uv[j][0] = osf->uv[corner_indices[j]][0];
392                 uv[j][1] = osf->uv[corner_indices[j]][1];
393         }
394         memcpy(osf->uv, uv, sizeof(osf->uv));
395 }
396
397 static void layerDefault_origspace_face(void *data, int count)
398 {
399         static OrigSpaceFace default_osf = {{{0, 0}, {1, 0}, {1, 1}, {0, 1}}};
400         OrigSpaceFace *osf = (OrigSpaceFace*)data;
401         int i;
402
403         for(i = 0; i < count; i++)
404                 osf[i] = default_osf;
405 }
406
407 static void layerSwap_mdisps(void *data, const int *ci)
408 {
409         MDisps *s = data;
410         float (*d)[3] = NULL;
411         int corners, cornersize, S;
412
413         if(s->disps) {
414                 int nverts= (ci[1] == 3) ? 4 : 3; /* silly way to know vertex count of face */
415                 corners= multires_mdisp_corners(s);
416                 cornersize= s->totdisp/corners;
417
418                 if(corners!=nverts) {
419                         /* happens when face changed vertex count in edit mode
420                            if it happened, just forgot displacement */
421
422                         MEM_freeN(s->disps);
423                         s->totdisp= (s->totdisp/corners)*nverts;
424                         s->disps= MEM_callocN(s->totdisp*sizeof(float)*3, "mdisp swap");
425                         return;
426                 }
427
428                 d= MEM_callocN(sizeof(float) * 3 * s->totdisp, "mdisps swap");
429
430                 for(S = 0; S < corners; S++)
431                         memcpy(d + cornersize*S, s->disps + cornersize*ci[S], cornersize*3*sizeof(float));
432                 
433                 MEM_freeN(s->disps);
434                 s->disps= d;
435         }
436 }
437
438 static void layerInterp_mdisps(void **sources, float *UNUSED(weights),
439                                 float *sub_weights, int count, void *dest)
440 {
441         MDisps *d = dest;
442         MDisps *s = NULL;
443         int st, stl;
444         int i, x, y;
445         int side, S, dst_corners, src_corners;
446         float crn_weight[4][2];
447         float (*sw)[4] = (void*)sub_weights;
448         float (*disps)[3], (*out)[3];
449
450         /* happens when flipping normals of newly created mesh */
451         if(!d->totdisp)
452                 return;
453
454         s = sources[0];
455         dst_corners = multires_mdisp_corners(d);
456         src_corners = multires_mdisp_corners(s);
457
458         if(sub_weights && count == 2 && src_corners == 3) {
459                 src_corners = multires_mdisp_corners(sources[1]);
460
461                 /* special case -- converting two triangles to quad */
462                 if(src_corners == 3 && dst_corners == 4) {
463                         MDisps tris[2];
464                         int vindex[4] = {0};
465
466                         for(i = 0; i < 2; i++)
467                                 for(y = 0; y < 4; y++)
468                                         for(x = 0; x < 4; x++)
469                                                 if(sw[x+i*4][y])
470                                                         vindex[x] = y;
471
472                         for(i = 0; i < 2; i++) {
473                                 float sw_m4[4][4] = {{0}};
474                                 int a = 7 & ~(1 << vindex[i*2] | 1 << vindex[i*2+1]);
475
476                                 sw_m4[0][vindex[i*2+1]] = 1;
477                                 sw_m4[1][vindex[i*2]] = 1;
478
479                                 for(x = 0; x < 3; x++)
480                                         if(a & (1 << x))
481                                                 sw_m4[2][x] = 1;
482
483                                 tris[i] = *((MDisps*)sources[i]);
484                                 tris[i].disps = MEM_dupallocN(tris[i].disps);
485                                 layerInterp_mdisps(&sources[i], NULL, (float*)sw_m4, 1, &tris[i]);
486                         }
487
488                         mdisp_join_tris(d, &tris[0], &tris[1]);
489
490                         for(i = 0; i < 2; i++)
491                                 MEM_freeN(tris[i].disps);
492
493                         return;
494                 }
495         }
496
497         /* For now, some restrictions on the input */
498         if(count != 1 || !sub_weights) {
499                 for(i = 0; i < d->totdisp; ++i)
500                         zero_v3(d->disps[i]);
501
502                 return;
503         }
504
505         /* Initialize the destination */
506         disps = MEM_callocN(3*d->totdisp*sizeof(float), "iterp disps");
507
508         side = sqrt(d->totdisp / dst_corners);
509         st = (side<<1)-1;
510         stl = st - 1;
511
512         sw= (void*)sub_weights;
513         for(i = 0; i < 4; ++i) {
514                 crn_weight[i][0] = 0 * sw[i][0] + stl * sw[i][1] + stl * sw[i][2] + 0 * sw[i][3];
515                 crn_weight[i][1] = 0 * sw[i][0] + 0 * sw[i][1] + stl * sw[i][2] + stl * sw[i][3];
516         }
517
518         multires_mdisp_smooth_bounds(s);
519
520         out = disps;
521         for(S = 0; S < dst_corners; S++) {
522                 float base[2], axis_x[2], axis_y[2];
523
524                 mdisp_apply_weight(S, dst_corners, 0, 0, st, crn_weight, &base[0], &base[1]);
525                 mdisp_apply_weight(S, dst_corners, side-1, 0, st, crn_weight, &axis_x[0], &axis_x[1]);
526                 mdisp_apply_weight(S, dst_corners, 0, side-1, st, crn_weight, &axis_y[0], &axis_y[1]);
527
528                 sub_v2_v2(axis_x, base);
529                 sub_v2_v2(axis_y, base);
530                 normalize_v2(axis_x);
531                 normalize_v2(axis_y);
532
533                 for(y = 0; y < side; ++y) {
534                         for(x = 0; x < side; ++x, ++out) {
535                                 int crn;
536                                 float face_u, face_v, crn_u, crn_v;
537
538                                 mdisp_apply_weight(S, dst_corners, x, y, st, crn_weight, &face_u, &face_v);
539                                 crn = mdisp_rot_face_to_quad_crn(src_corners, st, face_u, face_v, &crn_u, &crn_v);
540
541                                 old_mdisps_bilinear((*out), &s->disps[crn*side*side], side, crn_u, crn_v);
542                                 mdisp_flip_disp(crn, dst_corners, axis_x, axis_y, *out);
543                         }
544                 }
545         }
546
547         MEM_freeN(d->disps);
548         d->disps = disps;
549 }
550
551 static void layerCopy_mdisps(const void *source, void *dest, int count)
552 {
553         int i;
554         const MDisps *s = source;
555         MDisps *d = dest;
556
557         for(i = 0; i < count; ++i) {
558                 if(s[i].disps) {
559                         d[i].disps = MEM_dupallocN(s[i].disps);
560                         d[i].totdisp = s[i].totdisp;
561                 }
562                 else {
563                         d[i].disps = NULL;
564                         d[i].totdisp = 0;
565                 }
566                 
567         }
568 }
569
570 static void layerValidate_mdisps(void *data, int sub_elements)
571 {
572         MDisps *disps = data;
573         if(disps->disps) {
574                 int corners = multires_mdisp_corners(disps);
575
576                 if(corners != sub_elements) {
577                         MEM_freeN(disps->disps);
578                         disps->totdisp = disps->totdisp / corners * sub_elements;
579                         disps->disps = MEM_callocN(3*disps->totdisp*sizeof(float), "layerValidate_mdisps");
580                 }
581         }
582 }
583
584 static void layerFree_mdisps(void *data, int count, int UNUSED(size))
585 {
586         int i;
587         MDisps *d = data;
588
589         for(i = 0; i < count; ++i) {
590                 if(d[i].disps)
591                         MEM_freeN(d[i].disps);
592                 d[i].disps = NULL;
593                 d[i].totdisp = 0;
594         }
595 }
596
597 static int layerRead_mdisps(CDataFile *cdf, void *data, int count)
598 {
599         MDisps *d = data;
600         int i;
601
602         for(i = 0; i < count; ++i) {
603                 if(!d[i].disps)
604                         d[i].disps = MEM_callocN(sizeof(float)*3*d[i].totdisp, "mdisps read");
605
606                 if(!cdf_read_data(cdf, d[i].totdisp*3*sizeof(float), d[i].disps)) {
607                         printf("failed to read multires displacement %d/%d %d\n", i, count, d[i].totdisp);
608                         return 0;
609                 }
610         }
611
612         return 1;
613 }
614
615 static int layerWrite_mdisps(CDataFile *cdf, void *data, int count)
616 {
617         MDisps *d = data;
618         int i;
619
620         for(i = 0; i < count; ++i) {
621                 if(!cdf_write_data(cdf, d[i].totdisp*3*sizeof(float), d[i].disps)) {
622                         printf("failed to write multires displacement %d/%d %d\n", i, count, d[i].totdisp);
623                         return 0;
624                 }
625         }
626
627         return 1;
628 }
629
630 static size_t layerFilesize_mdisps(CDataFile *UNUSED(cdf), void *data, int count)
631 {
632         MDisps *d = data;
633         size_t size = 0;
634         int i;
635
636         for(i = 0; i < count; ++i)
637                 size += d[i].totdisp*3*sizeof(float);
638
639         return size;
640 }
641
642 /* --------- */
643
644 static void layerDefault_mloopcol(void *data, int count)
645 {
646         static MLoopCol default_mloopcol = {255,255,255,255};
647         MLoopCol *mlcol = (MLoopCol*)data;
648         int i;
649         for(i = 0; i < count; i++)
650                 mlcol[i] = default_mloopcol;
651
652 }
653
654 static void layerInterp_mloopcol(void **sources, float *weights,
655                                 float *sub_weights, int count, void *dest)
656 {
657         MLoopCol *mc = dest;
658         int i;
659         float *sub_weight;
660         struct {
661                 float a;
662                 float r;
663                 float g;
664                 float b;
665         } col;
666         col.a = col.r = col.g = col.b = 0;
667
668         sub_weight = sub_weights;
669         for(i = 0; i < count; ++i){
670                 float weight = weights ? weights[i] : 1;
671                 MLoopCol *src = sources[i];
672                 if(sub_weights){
673                         col.a += src->a * (*sub_weight) * weight;
674                         col.r += src->r * (*sub_weight) * weight;
675                         col.g += src->g * (*sub_weight) * weight;
676                         col.b += src->b * (*sub_weight) * weight;
677                         sub_weight++;           
678                 } else {
679                         col.a += src->a * weight;
680                         col.r += src->r * weight;
681                         col.g += src->g * weight;
682                         col.b += src->b * weight;
683                 }
684         }
685         
686         /* Subdivide smooth or fractal can cause problems without clamping
687          * although weights should also not cause this situation */
688         CLAMP(col.a, 0.0f, 255.0f);
689         CLAMP(col.r, 0.0f, 255.0f);
690         CLAMP(col.g, 0.0f, 255.0f);
691         CLAMP(col.b, 0.0f, 255.0f);
692         
693         mc->a = (int)col.a;
694         mc->r = (int)col.r;
695         mc->g = (int)col.g;
696         mc->b = (int)col.b;
697 }
698 static void layerInterp_mloopuv(void **sources, float *weights,
699                                 float *sub_weights, int count, void *dest)
700 {
701         MLoopUV *mluv = dest;
702         int i;
703         float *sub_weight;
704         struct {
705                 float u;
706                 float v;
707         }uv;
708         uv.u = uv.v = 0.0;
709
710         sub_weight = sub_weights;
711         for(i = 0; i < count; ++i){
712                 float weight = weights ? weights[i] : 1;
713                 MLoopUV *src = sources[i];
714                 if(sub_weights){
715                         uv.u += src->uv[0] * (*sub_weight) * weight;
716                         uv.v += src->uv[1] * (*sub_weight) * weight;
717                         sub_weight++;           
718                 } else {
719                         uv.u += src->uv[0] * weight;
720                         uv.v += src->uv[1] * weight;
721                 }
722         }
723         mluv->uv[0] = uv.u;
724         mluv->uv[1] = uv.v;
725 }
726
727 static void layerInterp_mcol(void **sources, float *weights,
728                                                          float *sub_weights, int count, void *dest)
729 {
730         MCol *mc = dest;
731         int i, j, k;
732         struct {
733                 float a;
734                 float r;
735                 float g;
736                 float b;
737         } col[4];
738         float *sub_weight;
739
740         if(count <= 0) return;
741
742         memset(col, 0, sizeof(col));
743         
744         sub_weight = sub_weights;
745         for(i = 0; i < count; ++i) {
746                 float weight = weights ? weights[i] : 1;
747
748                 for(j = 0; j < 4; ++j) {
749                         if(sub_weights) {
750                                 MCol *src = sources[i];
751                                 for(k = 0; k < 4; ++k, ++sub_weight, ++src) {
752                                         col[j].a += src->a * (*sub_weight) * weight;
753                                         col[j].r += src->r * (*sub_weight) * weight;
754                                         col[j].g += src->g * (*sub_weight) * weight;
755                                         col[j].b += src->b * (*sub_weight) * weight;
756                                 }
757                         } else {
758                                 MCol *src = sources[i];
759                                 col[j].a += src[j].a * weight;
760                                 col[j].r += src[j].r * weight;
761                                 col[j].g += src[j].g * weight;
762                                 col[j].b += src[j].b * weight;
763                         }
764                 }
765         }
766
767         for(j = 0; j < 4; ++j) {
768                 
769                 /* Subdivide smooth or fractal can cause problems without clamping
770                  * although weights should also not cause this situation */
771                 CLAMP(col[j].a, 0.0f, 255.0f);
772                 CLAMP(col[j].r, 0.0f, 255.0f);
773                 CLAMP(col[j].g, 0.0f, 255.0f);
774                 CLAMP(col[j].b, 0.0f, 255.0f);
775                 
776                 mc[j].a = (int)col[j].a;
777                 mc[j].r = (int)col[j].r;
778                 mc[j].g = (int)col[j].g;
779                 mc[j].b = (int)col[j].b;
780         }
781 }
782
783 static void layerSwap_mcol(void *data, const int *corner_indices)
784 {
785         MCol *mcol = data;
786         MCol col[4];
787         int j;
788
789         for(j = 0; j < 4; ++j)
790                 col[j] = mcol[corner_indices[j]];
791
792         memcpy(mcol, col, sizeof(col));
793 }
794
795 static void layerDefault_mcol(void *data, int count)
796 {
797         static MCol default_mcol = {255, 255, 255, 255};
798         MCol *mcol = (MCol*)data;
799         int i;
800
801         for(i = 0; i < 4*count; i++)
802                 mcol[i] = default_mcol;
803 }
804
805
806
807 static const LayerTypeInfo LAYERTYPEINFO[CD_NUMTYPES] = {
808         /* 0: CD_MVERT */
809         {sizeof(MVert), "MVert", 1, NULL, NULL, NULL, NULL, NULL, NULL},
810         /* 1: CD_MSTICKY */
811         {sizeof(MSticky), "MSticky", 1, NULL, NULL, NULL, layerInterp_msticky, NULL,
812          NULL},
813         /* 2: CD_MDEFORMVERT */
814         {sizeof(MDeformVert), "MDeformVert", 1, NULL, layerCopy_mdeformvert,
815          layerFree_mdeformvert, layerInterp_mdeformvert, NULL, NULL},
816         /* 3: CD_MEDGE */
817         {sizeof(MEdge), "MEdge", 1, NULL, NULL, NULL, NULL, NULL, NULL},
818         /* 4: CD_MFACE */
819         {sizeof(MFace), "MFace", 1, NULL, NULL, NULL, NULL, NULL, NULL},
820         /* 5: CD_MTFACE */
821         {sizeof(MTFace), "MTFace", 1, "UVMap", layerCopy_tface, NULL,
822          layerInterp_tface, layerSwap_tface, layerDefault_tface},
823         /* 6: CD_MCOL */
824         /* 4 MCol structs per face */
825         {sizeof(MCol)*4, "MCol", 4, "Col", NULL, NULL, layerInterp_mcol,
826          layerSwap_mcol, layerDefault_mcol},
827         /* 7: CD_ORIGINDEX */
828         {sizeof(int), "", 0, NULL, NULL, NULL, NULL, NULL, NULL},
829         /* 8: CD_NORMAL */
830         /* 3 floats per normal vector */
831         {sizeof(float)*3, "", 0, NULL, NULL, NULL, NULL, NULL, NULL},
832         /* 9: CD_POLYINDEX */
833         {sizeof(int), "MIntProperty", 1, NULL, NULL, NULL, NULL, NULL, NULL},
834         /* 10: CD_PROP_FLT */
835         {sizeof(MFloatProperty), "MFloatProperty",1,"Float",NULL,NULL,NULL,NULL},
836         /* 11: CD_PROP_INT */
837         {sizeof(MIntProperty), "MIntProperty",1,"Int",NULL,NULL,NULL,NULL},
838         /* 12: CD_PROP_STR */
839         {sizeof(MStringProperty), "MStringProperty",1,"String",NULL,NULL,NULL,NULL},
840         /* 13: CD_ORIGSPACE */
841         {sizeof(OrigSpaceFace), "OrigSpaceFace", 1, "UVMap", layerCopy_origspace_face, NULL,
842          layerInterp_origspace_face, layerSwap_origspace_face, layerDefault_origspace_face},
843         /* 14: CD_ORCO */
844         {sizeof(float)*3, "", 0, NULL, NULL, NULL, NULL, NULL, NULL},
845         /* 15: CD_MTEXPOLY */
846         {sizeof(MTexPoly), "MTexPoly", 1, "Face Texture", NULL, NULL, NULL, NULL, NULL},
847         /* 16: CD_MLOOPUV */
848         {sizeof(MLoopUV), "MLoopUV", 1, "UV coord", NULL, NULL, layerInterp_mloopuv, NULL, NULL},
849         /* 17: CD_MLOOPCOL */
850         {sizeof(MLoopCol), "MLoopCol", 1, "Col", NULL, NULL, layerInterp_mloopcol, NULL, layerDefault_mloopcol},
851         /* 18: CD_TANGENT */
852         {sizeof(float)*4*4, "", 0, NULL, NULL, NULL, NULL, NULL, NULL},
853         /* 19: CD_MDISPS */
854         {sizeof(MDisps), "MDisps", 1, NULL, layerCopy_mdisps,
855          layerFree_mdisps, layerInterp_mdisps, layerSwap_mdisps, NULL, layerRead_mdisps, layerWrite_mdisps,
856          layerFilesize_mdisps, layerValidate_mdisps},
857         /* 20: CD_WEIGHT_MCOL */
858         {sizeof(MCol)*4, "MCol", 4, "WeightCol", NULL, NULL, layerInterp_mcol,
859          layerSwap_mcol, layerDefault_mcol},
860         /* 21: CD_ID_MCOL */
861         {sizeof(MCol)*4, "MCol", 4, "IDCol", NULL, NULL, layerInterp_mcol,
862          layerSwap_mcol, layerDefault_mcol},
863         /* 22: CD_TEXTURE_MCOL */
864         {sizeof(MCol)*4, "MCol", 4, "TexturedCol", NULL, NULL, layerInterp_mcol,
865          layerSwap_mcol, layerDefault_mcol},
866         /* 23: CD_CLOTH_ORCO */
867         {sizeof(float)*3, "", 0, NULL, NULL, NULL, NULL, NULL, NULL},
868         /* 24: CD_RECAST */
869         {sizeof(MRecast), "MRecast", 1,"Recast",NULL,NULL,NULL,NULL}
870 };
871
872 static const char *LAYERTYPENAMES[CD_NUMTYPES] = {
873         /*   0-4 */ "CDMVert", "CDMSticky", "CDMDeformVert", "CDMEdge", "CDMFace",
874         /*   5-9 */ "CDMTFace", "CDMCol", "CDOrigIndex", "CDNormal", "CDFlags",
875         /* 10-14 */ "CDMFloatProperty", "CDMIntProperty","CDMStringProperty", "CDOrigSpace", "CDOrco",
876         /* 15-19 */ "CDMTexPoly", "CDMLoopUV", "CDMloopCol", "CDTangent", "CDMDisps",
877         /* 20-24 */"CDWeightMCol", "CDIDMCol", "CDTextureMCol", "CDClothOrco", "CDMRecast"
878 };
879
880 const CustomDataMask CD_MASK_BAREMESH =
881         CD_MASK_MVERT | CD_MASK_MEDGE | CD_MASK_MFACE;
882 const CustomDataMask CD_MASK_MESH =
883         CD_MASK_MVERT | CD_MASK_MEDGE | CD_MASK_MFACE |
884         CD_MASK_MSTICKY | CD_MASK_MDEFORMVERT | CD_MASK_MTFACE | CD_MASK_MCOL |
885         CD_MASK_PROP_FLT | CD_MASK_PROP_INT | CD_MASK_PROP_STR | CD_MASK_MDISPS | CD_MASK_RECAST;
886 const CustomDataMask CD_MASK_EDITMESH =
887         CD_MASK_MSTICKY | CD_MASK_MDEFORMVERT | CD_MASK_MTFACE |
888         CD_MASK_MCOL|CD_MASK_PROP_FLT | CD_MASK_PROP_INT | CD_MASK_PROP_STR | CD_MASK_MDISPS | CD_MASK_RECAST;
889 const CustomDataMask CD_MASK_DERIVEDMESH =
890         CD_MASK_MSTICKY | CD_MASK_MDEFORMVERT | CD_MASK_MTFACE |
891         CD_MASK_MCOL | CD_MASK_ORIGINDEX | CD_MASK_PROP_FLT | CD_MASK_PROP_INT | CD_MASK_CLOTH_ORCO |
892         CD_MASK_PROP_STR | CD_MASK_ORIGSPACE | CD_MASK_ORCO | CD_MASK_TANGENT | CD_MASK_WEIGHT_MCOL | CD_MASK_RECAST;
893 const CustomDataMask CD_MASK_BMESH = 
894         CD_MASK_MSTICKY | CD_MASK_MDEFORMVERT | CD_MASK_PROP_FLT | CD_MASK_PROP_INT | CD_MASK_PROP_STR;
895 const CustomDataMask CD_MASK_FACECORNERS =
896         CD_MASK_MTFACE | CD_MASK_MCOL | CD_MASK_MTEXPOLY | CD_MASK_MLOOPUV |
897         CD_MASK_MLOOPCOL;
898
899 static const LayerTypeInfo *layerType_getInfo(int type)
900 {
901         if(type < 0 || type >= CD_NUMTYPES) return NULL;
902
903         return &LAYERTYPEINFO[type];
904 }
905
906 static const char *layerType_getName(int type)
907 {
908         if(type < 0 || type >= CD_NUMTYPES) return NULL;
909
910         return LAYERTYPENAMES[type];
911 }
912
913 /********************* CustomData functions *********************/
914 static void customData_update_offsets(CustomData *data);
915
916 static CustomDataLayer *customData_add_layer__internal(CustomData *data,
917         int type, int alloctype, void *layerdata, int totelem, const char *name);
918
919 void CustomData_update_typemap(CustomData *data)
920 {
921         int i, lasttype = -1;
922
923         /* since we cant do in a pre-processor do here as an assert */
924         BLI_assert(sizeof(data->typemap) / sizeof(int) >= CD_NUMTYPES);
925
926         for (i=0; i<CD_NUMTYPES; i++) {
927                 data->typemap[i] = -1;
928         }
929
930         for (i=0; i<data->totlayer; i++) {
931                 if (data->layers[i].type != lasttype) {
932                         data->typemap[data->layers[i].type] = i;
933                 }
934                 lasttype = data->layers[i].type;
935         }
936 }
937
938 void CustomData_merge(const struct CustomData *source, struct CustomData *dest,
939                                           CustomDataMask mask, int alloctype, int totelem)
940 {
941         /*const LayerTypeInfo *typeInfo;*/
942         CustomDataLayer *layer, *newlayer;
943         int i, type, number = 0, lasttype = -1, lastactive = 0, lastrender = 0, lastclone = 0, lastmask = 0, lastflag = 0;
944
945         for(i = 0; i < source->totlayer; ++i) {
946                 layer = &source->layers[i];
947                 /*typeInfo = layerType_getInfo(layer->type);*/ /*UNUSED*/
948
949                 type = layer->type;
950
951                 if (type != lasttype) {
952                         number = 0;
953                         lastactive = layer->active;
954                         lastrender = layer->active_rnd;
955                         lastclone = layer->active_clone;
956                         lastmask = layer->active_mask;
957                         lasttype = type;
958                         lastflag = layer->flag;
959                 }
960                 else
961                         number++;
962
963                 if(lastflag & CD_FLAG_NOCOPY) continue;
964                 else if(!(mask & CD_TYPE_AS_MASK(type))) continue;
965                 else if(number < CustomData_number_of_layers(dest, type)) continue;
966
967                 if((alloctype == CD_ASSIGN) && (lastflag & CD_FLAG_NOFREE))
968                         newlayer = customData_add_layer__internal(dest, type, CD_REFERENCE,
969                                 layer->data, totelem, layer->name);
970                 else
971                         newlayer = customData_add_layer__internal(dest, type, alloctype,
972                                 layer->data, totelem, layer->name);
973                 
974                 if(newlayer) {
975                         newlayer->active = lastactive;
976                         newlayer->active_rnd = lastrender;
977                         newlayer->active_clone = lastclone;
978                         newlayer->active_mask = lastmask;
979                         newlayer->flag |= lastflag & (CD_FLAG_EXTERNAL|CD_FLAG_IN_MEMORY);
980                 }
981         }
982
983         CustomData_update_typemap(dest);
984 }
985
986 void CustomData_copy(const struct CustomData *source, struct CustomData *dest,
987                                          CustomDataMask mask, int alloctype, int totelem)
988 {
989         memset(dest, 0, sizeof(*dest));
990
991         if(source->external)
992                 dest->external= MEM_dupallocN(source->external);
993
994         CustomData_merge(source, dest, mask, alloctype, totelem);
995 }
996
997 static void customData_free_layer__internal(CustomDataLayer *layer, int totelem)
998 {
999         const LayerTypeInfo *typeInfo;
1000
1001         if(!(layer->flag & CD_FLAG_NOFREE) && layer->data) {
1002                 typeInfo = layerType_getInfo(layer->type);
1003
1004                 if(typeInfo->free)
1005                         typeInfo->free(layer->data, totelem, typeInfo->size);
1006
1007                 if(layer->data)
1008                         MEM_freeN(layer->data);
1009         }
1010 }
1011
1012 static void CustomData_external_free(CustomData *data)
1013 {
1014         if(data->external) {
1015                 MEM_freeN(data->external);
1016                 data->external= NULL;
1017         }
1018 }
1019
1020 void CustomData_free(CustomData *data, int totelem)
1021 {
1022         int i;
1023
1024         for(i = 0; i < data->totlayer; ++i)
1025                 customData_free_layer__internal(&data->layers[i], totelem);
1026
1027         if(data->layers)
1028                 MEM_freeN(data->layers);
1029         
1030         CustomData_external_free(data);
1031         
1032         memset(data, 0, sizeof(*data));
1033 }
1034
1035 static void customData_update_offsets(CustomData *data)
1036 {
1037         const LayerTypeInfo *typeInfo;
1038         int i, offset = 0;
1039
1040         for(i = 0; i < data->totlayer; ++i) {
1041                 typeInfo = layerType_getInfo(data->layers[i].type);
1042
1043                 data->layers[i].offset = offset;
1044                 offset += typeInfo->size;
1045         }
1046
1047         data->totsize = offset;
1048         CustomData_update_typemap(data);
1049 }
1050
1051 int CustomData_get_layer_index(const CustomData *data, int type)
1052 {
1053         int i; 
1054
1055         for(i=0; i < data->totlayer; ++i)
1056                 if(data->layers[i].type == type)
1057                         return i;
1058
1059         return -1;
1060 }
1061
1062 int CustomData_get_layer_index_n(const struct CustomData *data, int type, int n)
1063 {
1064         int i = CustomData_get_layer_index(data, type);
1065
1066         if (i != -1) {
1067                 i = (data->layers[i + n].type == type) ? (i + n) : (-1);
1068         }
1069
1070         return i;
1071 }
1072
1073 int CustomData_get_named_layer_index(const CustomData *data, int type, const char *name)
1074 {
1075         int i;
1076
1077         for(i=0; i < data->totlayer; ++i)
1078                 if(data->layers[i].type == type && strcmp(data->layers[i].name, name)==0)
1079                         return i;
1080
1081         return -1;
1082 }
1083
1084 int CustomData_get_active_layer_index(const CustomData *data, int type)
1085 {
1086         if (!data->totlayer)
1087                 return -1;
1088
1089         if (data->typemap[type] != -1) {
1090                 return data->typemap[type] + data->layers[data->typemap[type]].active;
1091         }
1092
1093         return -1;
1094 }
1095
1096 int CustomData_get_render_layer_index(const CustomData *data, int type)
1097 {
1098         int i;
1099
1100         for(i=0; i < data->totlayer; ++i)
1101                 if(data->layers[i].type == type)
1102                         return i + data->layers[i].active_rnd;
1103
1104         return -1;
1105 }
1106
1107 int CustomData_get_clone_layer_index(const CustomData *data, int type)
1108 {
1109         int i;
1110
1111         for(i=0; i < data->totlayer; ++i)
1112                 if(data->layers[i].type == type)
1113                         return i + data->layers[i].active_clone;
1114
1115         return -1;
1116 }
1117
1118 int CustomData_get_stencil_layer_index(const CustomData *data, int type)
1119 {
1120         int i;
1121
1122         for(i=0; i < data->totlayer; ++i)
1123                 if(data->layers[i].type == type)
1124                         return i + data->layers[i].active_mask;
1125
1126         return -1;
1127 }
1128
1129 int CustomData_get_active_layer(const CustomData *data, int type)
1130 {
1131         int i;
1132
1133         for(i=0; i < data->totlayer; ++i)
1134                 if(data->layers[i].type == type)
1135                         return data->layers[i].active;
1136
1137         return -1;
1138 }
1139
1140 int CustomData_get_render_layer(const CustomData *data, int type)
1141 {
1142         int i;
1143
1144         for(i=0; i < data->totlayer; ++i)
1145                 if(data->layers[i].type == type)
1146                         return data->layers[i].active_rnd;
1147
1148         return -1;
1149 }
1150
1151 int CustomData_get_clone_layer(const CustomData *data, int type)
1152 {
1153         int i;
1154
1155         for(i=0; i < data->totlayer; ++i)
1156                 if(data->layers[i].type == type)
1157                         return data->layers[i].active_clone;
1158
1159         return -1;
1160 }
1161
1162 int CustomData_get_stencil_layer(const CustomData *data, int type)
1163 {
1164         int i;
1165
1166         for(i=0; i < data->totlayer; ++i)
1167                 if(data->layers[i].type == type)
1168                         return data->layers[i].active_mask;
1169
1170         return -1;
1171 }
1172
1173 void CustomData_set_layer_active(CustomData *data, int type, int n)
1174 {
1175         int i;
1176
1177         for(i=0; i < data->totlayer; ++i)
1178                 if(data->layers[i].type == type)
1179                         data->layers[i].active = n;
1180 }
1181
1182 void CustomData_set_layer_render(CustomData *data, int type, int n)
1183 {
1184         int i;
1185
1186         for(i=0; i < data->totlayer; ++i)
1187                 if(data->layers[i].type == type)
1188                         data->layers[i].active_rnd = n;
1189 }
1190
1191 void CustomData_set_layer_clone(CustomData *data, int type, int n)
1192 {
1193         int i;
1194
1195         for(i=0; i < data->totlayer; ++i)
1196                 if(data->layers[i].type == type)
1197                         data->layers[i].active_clone = n;
1198 }
1199
1200 void CustomData_set_layer_stencil(CustomData *data, int type, int n)
1201 {
1202         int i;
1203
1204         for(i=0; i < data->totlayer; ++i)
1205                 if(data->layers[i].type == type)
1206                         data->layers[i].active_mask = n;
1207 }
1208
1209 /* for using with an index from CustomData_get_active_layer_index and CustomData_get_render_layer_index */
1210 void CustomData_set_layer_active_index(CustomData *data, int type, int n)
1211 {
1212         int i;
1213
1214         for(i=0; i < data->totlayer; ++i)
1215                 if(data->layers[i].type == type)
1216                         data->layers[i].active = n-i;
1217 }
1218
1219 void CustomData_set_layer_render_index(CustomData *data, int type, int n)
1220 {
1221         int i;
1222
1223         for(i=0; i < data->totlayer; ++i)
1224                 if(data->layers[i].type == type)
1225                         data->layers[i].active_rnd = n-i;
1226 }
1227
1228 void CustomData_set_layer_clone_index(CustomData *data, int type, int n)
1229 {
1230         int i;
1231
1232         for(i=0; i < data->totlayer; ++i)
1233                 if(data->layers[i].type == type)
1234                         data->layers[i].active_clone = n-i;
1235 }
1236
1237 void CustomData_set_layer_stencil_index(CustomData *data, int type, int n)
1238 {
1239         int i;
1240
1241         for(i=0; i < data->totlayer; ++i)
1242                 if(data->layers[i].type == type)
1243                         data->layers[i].active_mask = n-i;
1244 }
1245
1246 void CustomData_set_layer_flag(struct CustomData *data, int type, int flag)
1247 {
1248         int i;
1249
1250         for(i=0; i < data->totlayer; ++i)
1251                 if(data->layers[i].type == type)
1252                         data->layers[i].flag |= flag;
1253 }
1254
1255 static int customData_resize(CustomData *data, int amount)
1256 {
1257         CustomDataLayer *tmp = MEM_callocN(sizeof(*tmp)*(data->maxlayer + amount),
1258                                                                            "CustomData->layers");
1259         if(!tmp) return 0;
1260
1261         data->maxlayer += amount;
1262         if (data->layers) {
1263                 memcpy(tmp, data->layers, sizeof(*tmp) * data->totlayer);
1264                 MEM_freeN(data->layers);
1265         }
1266         data->layers = tmp;
1267
1268         return 1;
1269 }
1270
1271 static CustomDataLayer *customData_add_layer__internal(CustomData *data,
1272         int type, int alloctype, void *layerdata, int totelem, const char *name)
1273 {
1274         const LayerTypeInfo *typeInfo= layerType_getInfo(type);
1275         int size = typeInfo->size * totelem, flag = 0, index = data->totlayer;
1276         void *newlayerdata;
1277
1278         if (!typeInfo->defaultname && CustomData_has_layer(data, type))
1279                 return &data->layers[CustomData_get_layer_index(data, type)];
1280
1281         if((alloctype == CD_ASSIGN) || (alloctype == CD_REFERENCE)) {
1282                 newlayerdata = layerdata;
1283         }
1284         else {
1285                 newlayerdata = MEM_callocN(size, layerType_getName(type));
1286                 if(!newlayerdata)
1287                         return NULL;
1288         }
1289
1290         if (alloctype == CD_DUPLICATE) {
1291                 if(typeInfo->copy)
1292                         typeInfo->copy(layerdata, newlayerdata, totelem);
1293                 else
1294                         memcpy(newlayerdata, layerdata, size);
1295         }
1296         else if (alloctype == CD_DEFAULT) {
1297                 if(typeInfo->set_default)
1298                         typeInfo->set_default((char*)newlayerdata, totelem);
1299         }
1300         else if (alloctype == CD_REFERENCE)
1301                 flag |= CD_FLAG_NOFREE;
1302
1303         if(index >= data->maxlayer) {
1304                 if(!customData_resize(data, CUSTOMDATA_GROW)) {
1305                         if(newlayerdata != layerdata)
1306                                 MEM_freeN(newlayerdata);
1307                         return NULL;
1308                 }
1309         }
1310         
1311         data->totlayer++;
1312
1313         /* keep layers ordered by type */
1314         for( ; index > 0 && data->layers[index - 1].type > type; --index)
1315                 data->layers[index] = data->layers[index - 1];
1316
1317         data->layers[index].type = type;
1318         data->layers[index].flag = flag;
1319         data->layers[index].data = newlayerdata;
1320
1321         if(name || (name=typeInfo->defaultname)) {
1322                 BLI_strncpy(data->layers[index].name, name, 32);
1323                 CustomData_set_layer_unique_name(data, index);
1324         }
1325         else
1326                 data->layers[index].name[0] = '\0';
1327
1328         if(index > 0 && data->layers[index-1].type == type) {
1329                 data->layers[index].active = data->layers[index-1].active;
1330                 data->layers[index].active_rnd = data->layers[index-1].active_rnd;
1331                 data->layers[index].active_clone = data->layers[index-1].active_clone;
1332                 data->layers[index].active_mask = data->layers[index-1].active_mask;
1333         } else {
1334                 data->layers[index].active = 0;
1335                 data->layers[index].active_rnd = 0;
1336                 data->layers[index].active_clone = 0;
1337                 data->layers[index].active_mask = 0;
1338         }
1339         
1340         customData_update_offsets(data);
1341
1342         return &data->layers[index];
1343 }
1344
1345 void *CustomData_add_layer(CustomData *data, int type, int alloctype,
1346                                                    void *layerdata, int totelem)
1347 {
1348         CustomDataLayer *layer;
1349         const LayerTypeInfo *typeInfo= layerType_getInfo(type);
1350         
1351         layer = customData_add_layer__internal(data, type, alloctype, layerdata,
1352                                                                                    totelem, typeInfo->defaultname);
1353         CustomData_update_typemap(data);
1354
1355         if(layer)
1356                 return layer->data;
1357
1358         return NULL;
1359 }
1360
1361 /*same as above but accepts a name*/
1362 void *CustomData_add_layer_named(CustomData *data, int type, int alloctype,
1363                                                    void *layerdata, int totelem, const char *name)
1364 {
1365         CustomDataLayer *layer;
1366         
1367         layer = customData_add_layer__internal(data, type, alloctype, layerdata,
1368                                                                                    totelem, name);
1369         CustomData_update_typemap(data);
1370
1371         if(layer)
1372                 return layer->data;
1373
1374         return NULL;
1375 }
1376
1377
1378 int CustomData_free_layer(CustomData *data, int type, int totelem, int index)
1379 {
1380         int i;
1381         
1382         if (index < 0) return 0;
1383
1384         customData_free_layer__internal(&data->layers[index], totelem);
1385
1386         for (i=index+1; i < data->totlayer; ++i)
1387                 data->layers[i-1] = data->layers[i];
1388
1389         data->totlayer--;
1390
1391         /* if layer was last of type in array, set new active layer */
1392         if ((index >= data->totlayer) || (data->layers[index].type != type)) {
1393                 i = CustomData_get_layer_index(data, type);
1394                 
1395                 if (i >= 0)
1396                         for (; i < data->totlayer && data->layers[i].type == type; i++) {
1397                                 data->layers[i].active--;
1398                                 data->layers[i].active_rnd--;
1399                                 data->layers[i].active_clone--;
1400                                 data->layers[i].active_mask--;
1401                         }
1402         }
1403
1404         if (data->totlayer <= data->maxlayer-CUSTOMDATA_GROW)
1405                 customData_resize(data, -CUSTOMDATA_GROW);
1406
1407         customData_update_offsets(data);
1408         CustomData_update_typemap(data);
1409
1410         return 1;
1411 }
1412
1413 int CustomData_free_layer_active(CustomData *data, int type, int totelem)
1414 {
1415         int index = 0;
1416         index = CustomData_get_active_layer_index(data, type);
1417         if (index < 0) return 0;
1418         return CustomData_free_layer(data, type, totelem, index);
1419 }
1420
1421
1422 void CustomData_free_layers(CustomData *data, int type, int totelem)
1423 {
1424         while (CustomData_has_layer(data, type))
1425                 CustomData_free_layer_active(data, type, totelem);
1426 }
1427
1428 int CustomData_has_layer(const CustomData *data, int type)
1429 {
1430         return (CustomData_get_layer_index(data, type) != -1);
1431 }
1432
1433 int CustomData_number_of_layers(const CustomData *data, int type)
1434 {
1435         int i, number = 0;
1436
1437         for(i = 0; i < data->totlayer; i++)
1438                 if(data->layers[i].type == type)
1439                         number++;
1440         
1441         return number;
1442 }
1443
1444 void *CustomData_duplicate_referenced_layer(struct CustomData *data, const int type, const int totelem)
1445 {
1446         CustomDataLayer *layer;
1447         int layer_index;
1448
1449         /* get the layer index of the first layer of type */
1450         layer_index = CustomData_get_active_layer_index(data, type);
1451         if(layer_index < 0) return NULL;
1452
1453         layer = &data->layers[layer_index];
1454
1455         if (layer->flag & CD_FLAG_NOFREE) {
1456                 /* MEM_dupallocN won’t work in case of complex layers, like e.g.
1457                  * CD_MDEFORMVERT, which has pointers to allocated data...
1458                  * So in case a custom copy function is defined, use it!
1459                  */
1460                 const LayerTypeInfo *typeInfo = layerType_getInfo(layer->type);
1461
1462                 if(typeInfo->copy) {
1463                         char *dest_data = MEM_mallocN(typeInfo->size * totelem, "CD duplicate ref layer");
1464                         typeInfo->copy(layer->data, dest_data, totelem);
1465                         layer->data = dest_data;
1466                 }
1467                 else
1468                         layer->data = MEM_dupallocN(layer->data);
1469
1470                 layer->flag &= ~CD_FLAG_NOFREE;
1471         }
1472
1473         return layer->data;
1474 }
1475
1476 void *CustomData_duplicate_referenced_layer_named(struct CustomData *data,
1477                                                                                                   const int type, const char *name, const int totelem)
1478 {
1479         CustomDataLayer *layer;
1480         int layer_index;
1481
1482         /* get the layer index of the desired layer */
1483         layer_index = CustomData_get_named_layer_index(data, type, name);
1484         if(layer_index < 0) return NULL;
1485
1486         layer = &data->layers[layer_index];
1487
1488         if (layer->flag & CD_FLAG_NOFREE) {
1489                 /* MEM_dupallocN won’t work in case of complex layers, like e.g.
1490                  * CD_MDEFORMVERT, which has pointers to allocated data...
1491                  * So in case a custom copy function is defined, use it!
1492                  */
1493                 const LayerTypeInfo *typeInfo = layerType_getInfo(layer->type);
1494
1495                 if(typeInfo->copy) {
1496                         char *dest_data = MEM_mallocN(typeInfo->size * totelem, "CD duplicate ref layer");
1497                         typeInfo->copy(layer->data, dest_data, totelem);
1498                         layer->data = dest_data;
1499                 }
1500                 else
1501                         layer->data = MEM_dupallocN(layer->data);
1502
1503                 layer->flag &= ~CD_FLAG_NOFREE;
1504         }
1505
1506         return layer->data;
1507 }
1508
1509 int CustomData_is_referenced_layer(struct CustomData *data, int type)
1510 {
1511         CustomDataLayer *layer;
1512         int layer_index;
1513
1514         /* get the layer index of the first layer of type */
1515         layer_index = CustomData_get_active_layer_index(data, type);
1516         if(layer_index < 0) return 0;
1517
1518         layer = &data->layers[layer_index];
1519
1520         return (layer->flag & CD_FLAG_NOFREE) != 0;
1521 }
1522
1523 void CustomData_free_temporary(CustomData *data, int totelem)
1524 {
1525         CustomDataLayer *layer;
1526         int i, j;
1527
1528         for(i = 0, j = 0; i < data->totlayer; ++i) {
1529                 layer = &data->layers[i];
1530
1531                 if (i != j)
1532                         data->layers[j] = data->layers[i];
1533
1534                 if ((layer->flag & CD_FLAG_TEMPORARY) == CD_FLAG_TEMPORARY)
1535                         customData_free_layer__internal(layer, totelem);
1536                 else
1537                         j++;
1538         }
1539
1540         data->totlayer = j;
1541
1542         if(data->totlayer <= data->maxlayer-CUSTOMDATA_GROW)
1543                 customData_resize(data, -CUSTOMDATA_GROW);
1544
1545         customData_update_offsets(data);
1546 }
1547
1548 void CustomData_set_only_copy(const struct CustomData *data,
1549                               CustomDataMask mask)
1550 {
1551         int i;
1552
1553         for(i = 0; i < data->totlayer; ++i)
1554                 if(!(mask & CD_TYPE_AS_MASK(data->layers[i].type)))
1555                         data->layers[i].flag |= CD_FLAG_NOCOPY;
1556 }
1557
1558 void CustomData_copy_elements(int type, void *source, void *dest, int count)
1559 {
1560         const LayerTypeInfo *typeInfo = layerType_getInfo(type);
1561
1562         if (typeInfo->copy)
1563                 typeInfo->copy(source, dest, count);
1564         else
1565                 memcpy(dest, source, typeInfo->size*count);
1566 }
1567
1568 void CustomData_copy_data(const CustomData *source, CustomData *dest,
1569                                                   int source_index, int dest_index, int count)
1570 {
1571         const LayerTypeInfo *typeInfo;
1572         int src_i, dest_i;
1573         int src_offset;
1574         int dest_offset;
1575
1576         /* copies a layer at a time */
1577         dest_i = 0;
1578         for(src_i = 0; src_i < source->totlayer; ++src_i) {
1579
1580                 /* find the first dest layer with type >= the source type
1581                  * (this should work because layers are ordered by type)
1582                  */
1583                 while(dest_i < dest->totlayer
1584                           && dest->layers[dest_i].type < source->layers[src_i].type)
1585                         ++dest_i;
1586
1587                 /* if there are no more dest layers, we're done */
1588                 if(dest_i >= dest->totlayer) return;
1589
1590                 /* if we found a matching layer, copy the data */
1591                 if(dest->layers[dest_i].type == source->layers[src_i].type) {
1592                         char *src_data = source->layers[src_i].data;
1593                         char *dest_data = dest->layers[dest_i].data;
1594
1595                         typeInfo = layerType_getInfo(source->layers[src_i].type);
1596
1597                         src_offset = source_index * typeInfo->size;
1598                         dest_offset = dest_index * typeInfo->size;
1599                         
1600                         if (!src_data || !dest_data) {
1601                                 printf("%s: warning null data for %s type (%p --> %p), skipping\n",
1602                                        __func__, layerType_getName(source->layers[src_i].type),
1603                                        (void *)src_data, (void *)dest_data);
1604                                 continue;
1605                         }
1606                         
1607                         if(typeInfo->copy)
1608                                 typeInfo->copy(src_data + src_offset,
1609                                                                 dest_data + dest_offset,
1610                                                                 count);
1611                         else
1612                                 memcpy(dest_data + dest_offset,
1613                                            src_data + src_offset,
1614                                            count * typeInfo->size);
1615
1616                         /* if there are multiple source & dest layers of the same type,
1617                          * we don't want to copy all source layers to the same dest, so
1618                          * increment dest_i
1619                          */
1620                         ++dest_i;
1621                 }
1622         }
1623 }
1624
1625 void CustomData_free_elem(CustomData *data, int index, int count)
1626 {
1627         int i;
1628         const LayerTypeInfo *typeInfo;
1629
1630         for(i = 0; i < data->totlayer; ++i) {
1631                 if(!(data->layers[i].flag & CD_FLAG_NOFREE)) {
1632                         typeInfo = layerType_getInfo(data->layers[i].type);
1633
1634                         if(typeInfo->free) {
1635                                 int offset = typeInfo->size * index;
1636
1637                                 typeInfo->free((char *)data->layers[i].data + offset,
1638                                                            count, typeInfo->size);
1639                         }
1640                 }
1641         }
1642 }
1643
1644 #define SOURCE_BUF_SIZE 100
1645
1646 void CustomData_interp(const CustomData *source, CustomData *dest,
1647                                            int *src_indices, float *weights, float *sub_weights,
1648                                            int count, int dest_index)
1649 {
1650         int src_i, dest_i;
1651         int dest_offset;
1652         int j;
1653         void *source_buf[SOURCE_BUF_SIZE];
1654         void **sources = source_buf;
1655
1656         /* slow fallback in case we're interpolating a ridiculous number of
1657          * elements
1658          */
1659         if(count > SOURCE_BUF_SIZE)
1660                 sources = MEM_callocN(sizeof(*sources) * count,
1661                                                           "CustomData_interp sources");
1662
1663         /* interpolates a layer at a time */
1664         dest_i = 0;
1665         for(src_i = 0; src_i < source->totlayer; ++src_i) {
1666                 const LayerTypeInfo *typeInfo= layerType_getInfo(source->layers[src_i].type);
1667                 if(!typeInfo->interp) continue;
1668
1669                 /* find the first dest layer with type >= the source type
1670                  * (this should work because layers are ordered by type)
1671                  */
1672                 while(dest_i < dest->totlayer
1673                           && dest->layers[dest_i].type < source->layers[src_i].type)
1674                         ++dest_i;
1675
1676                 /* if there are no more dest layers, we're done */
1677                 if(dest_i >= dest->totlayer) return;
1678
1679                 /* if we found a matching layer, copy the data */
1680                 if(dest->layers[dest_i].type == source->layers[src_i].type) {
1681                         void *src_data = source->layers[src_i].data;
1682
1683                         for(j = 0; j < count; ++j)
1684                                 sources[j] = (char *)src_data
1685                                                          + typeInfo->size * src_indices[j];
1686
1687                         dest_offset = dest_index * typeInfo->size;
1688
1689                         typeInfo->interp(sources, weights, sub_weights, count,
1690                                                    (char *)dest->layers[dest_i].data + dest_offset);
1691
1692                         /* if there are multiple source & dest layers of the same type,
1693                          * we don't want to copy all source layers to the same dest, so
1694                          * increment dest_i
1695                          */
1696                         ++dest_i;
1697                 }
1698         }
1699
1700         if(count > SOURCE_BUF_SIZE) MEM_freeN(sources);
1701 }
1702
1703 void CustomData_swap(struct CustomData *data, int index, const int *corner_indices)
1704 {
1705         const LayerTypeInfo *typeInfo;
1706         int i;
1707
1708         for(i = 0; i < data->totlayer; ++i) {
1709                 typeInfo = layerType_getInfo(data->layers[i].type);
1710
1711                 if(typeInfo->swap) {
1712                         int offset = typeInfo->size * index;
1713
1714                         typeInfo->swap((char *)data->layers[i].data + offset, corner_indices);
1715                 }
1716         }
1717 }
1718
1719 void *CustomData_get(const CustomData *data, int index, int type)
1720 {
1721         int offset;
1722         int layer_index;
1723         
1724         /* get the layer index of the active layer of type */
1725         layer_index = CustomData_get_active_layer_index(data, type);
1726         if(layer_index < 0) return NULL;
1727
1728         /* get the offset of the desired element */
1729         offset = layerType_getInfo(type)->size * index;
1730
1731         return (char *)data->layers[layer_index].data + offset;
1732 }
1733
1734 void *CustomData_get_n(const CustomData *data, int type, int index, int n)
1735 {
1736         int layer_index;
1737         int offset;
1738
1739         /* get the layer index of the first layer of type */
1740         layer_index = data->typemap[type];
1741         if(layer_index < 0) return NULL;
1742
1743         offset = layerType_getInfo(type)->size * index;
1744         return (char *)data->layers[layer_index+n].data + offset;
1745 }
1746
1747 void *CustomData_get_layer(const CustomData *data, int type)
1748 {
1749         /* get the layer index of the active layer of type */
1750         int layer_index = CustomData_get_active_layer_index(data, type);
1751         if(layer_index < 0) return NULL;
1752
1753         return data->layers[layer_index].data;
1754 }
1755
1756 void *CustomData_get_layer_n(const CustomData *data, int type, int n)
1757 {
1758         /* get the layer index of the active layer of type */
1759         int layer_index = CustomData_get_layer_index_n(data, type, n);
1760         if(layer_index < 0) return NULL;
1761
1762         return data->layers[layer_index].data;
1763 }
1764
1765 void *CustomData_get_layer_named(const struct CustomData *data, int type,
1766                                                                  const char *name)
1767 {
1768         int layer_index = CustomData_get_named_layer_index(data, type, name);
1769         if(layer_index < 0) return NULL;
1770
1771         return data->layers[layer_index].data;
1772 }
1773
1774
1775 int CustomData_set_layer_name(const CustomData *data, int type, int n, const char *name)
1776 {
1777         /* get the layer index of the first layer of type */
1778         int layer_index = CustomData_get_layer_index_n(data, type, n);
1779
1780         if(layer_index < 0) return 0;
1781         if (!name) return 0;
1782         
1783         strcpy(data->layers[layer_index].name, name);
1784         
1785         return 1;
1786 }
1787
1788 void *CustomData_set_layer(const CustomData *data, int type, void *ptr)
1789 {
1790         /* get the layer index of the first layer of type */
1791         int layer_index = CustomData_get_active_layer_index(data, type);
1792
1793         if(layer_index < 0) return NULL;
1794
1795         data->layers[layer_index].data = ptr;
1796
1797         return ptr;
1798 }
1799
1800 void *CustomData_set_layer_n(const struct CustomData *data, int type, int n, void *ptr)
1801 {
1802         /* get the layer index of the first layer of type */
1803         int layer_index = CustomData_get_layer_index_n(data, type, n);
1804         if(layer_index < 0) return NULL;
1805
1806         data->layers[layer_index].data = ptr;
1807
1808         return ptr;
1809 }
1810
1811 void CustomData_set(const CustomData *data, int index, int type, void *source)
1812 {
1813         void *dest = CustomData_get(data, index, type);
1814         const LayerTypeInfo *typeInfo = layerType_getInfo(type);
1815
1816         if(!dest) return;
1817
1818         if(typeInfo->copy)
1819                 typeInfo->copy(source, dest, 1);
1820         else
1821                 memcpy(dest, source, typeInfo->size);
1822 }
1823
1824 /* EditMesh functions */
1825
1826 void CustomData_em_free_block(CustomData *data, void **block)
1827 {
1828         const LayerTypeInfo *typeInfo;
1829         int i;
1830
1831         if(!*block) return;
1832
1833         for(i = 0; i < data->totlayer; ++i) {
1834                 if(!(data->layers[i].flag & CD_FLAG_NOFREE)) {
1835                         typeInfo = layerType_getInfo(data->layers[i].type);
1836
1837                         if(typeInfo->free) {
1838                                 int offset = data->layers[i].offset;
1839                                 typeInfo->free((char*)*block + offset, 1, typeInfo->size);
1840                         }
1841                 }
1842         }
1843
1844         MEM_freeN(*block);
1845         *block = NULL;
1846 }
1847
1848 static void CustomData_em_alloc_block(CustomData *data, void **block)
1849 {
1850         /* TODO: optimize free/alloc */
1851
1852         if (*block)
1853                 CustomData_em_free_block(data, block);
1854
1855         if (data->totsize > 0)
1856                 *block = MEM_callocN(data->totsize, "CustomData EM block");
1857         else
1858                 *block = NULL;
1859 }
1860
1861 void CustomData_em_copy_data(const CustomData *source, CustomData *dest,
1862                                                         void *src_block, void **dest_block)
1863 {
1864         const LayerTypeInfo *typeInfo;
1865         int dest_i, src_i;
1866
1867         if (!*dest_block)
1868                 CustomData_em_alloc_block(dest, dest_block);
1869         
1870         /* copies a layer at a time */
1871         dest_i = 0;
1872         for(src_i = 0; src_i < source->totlayer; ++src_i) {
1873
1874                 /* find the first dest layer with type >= the source type
1875                  * (this should work because layers are ordered by type)
1876                  */
1877                 while(dest_i < dest->totlayer
1878                           && dest->layers[dest_i].type < source->layers[src_i].type)
1879                         ++dest_i;
1880
1881                 /* if there are no more dest layers, we're done */
1882                 if(dest_i >= dest->totlayer) return;
1883
1884                 /* if we found a matching layer, copy the data */
1885                 if(dest->layers[dest_i].type == source->layers[src_i].type &&
1886                         strcmp(dest->layers[dest_i].name, source->layers[src_i].name) == 0) {
1887                         char *src_data = (char*)src_block + source->layers[src_i].offset;
1888                         char *dest_data = (char*)*dest_block + dest->layers[dest_i].offset;
1889
1890                         typeInfo = layerType_getInfo(source->layers[src_i].type);
1891
1892                         if(typeInfo->copy)
1893                                 typeInfo->copy(src_data, dest_data, 1);
1894                         else
1895                                 memcpy(dest_data, src_data, typeInfo->size);
1896
1897                         /* if there are multiple source & dest layers of the same type,
1898                          * we don't want to copy all source layers to the same dest, so
1899                          * increment dest_i
1900                          */
1901                         ++dest_i;
1902                 }
1903         }
1904 }
1905
1906 void CustomData_em_validate_data(CustomData *data, void *block, int sub_elements)
1907 {
1908         int i;
1909         for(i = 0; i < data->totlayer; i++) {
1910                 const LayerTypeInfo *typeInfo = layerType_getInfo(data->layers[i].type);
1911                 char *leayer_data = (char*)block + data->layers[i].offset;
1912
1913                 if(typeInfo->validate)
1914                         typeInfo->validate(leayer_data, sub_elements);
1915         }
1916 }
1917
1918 void *CustomData_em_get(const CustomData *data, void *block, int type)
1919 {
1920         int layer_index;
1921         
1922         /* get the layer index of the first layer of type */
1923         layer_index = CustomData_get_active_layer_index(data, type);
1924         if(layer_index < 0) return NULL;
1925
1926         return (char *)block + data->layers[layer_index].offset;
1927 }
1928
1929 void *CustomData_em_get_n(const CustomData *data, void *block, int type, int n)
1930 {
1931         int layer_index;
1932         
1933         /* get the layer index of the first layer of type */
1934         layer_index = CustomData_get_layer_index_n(data, type, n);
1935         if(layer_index < 0) return NULL;
1936
1937         return (char *)block + data->layers[layer_index].offset;
1938 }
1939
1940 void CustomData_em_set(CustomData *data, void *block, int type, void *source)
1941 {
1942         void *dest = CustomData_em_get(data, block, type);
1943         const LayerTypeInfo *typeInfo = layerType_getInfo(type);
1944
1945         if(!dest) return;
1946
1947         if(typeInfo->copy)
1948                 typeInfo->copy(source, dest, 1);
1949         else
1950                 memcpy(dest, source, typeInfo->size);
1951 }
1952
1953 void CustomData_em_set_n(CustomData *data, void *block, int type, int n, void *source)
1954 {
1955         void *dest = CustomData_em_get_n(data, block, type, n);
1956         const LayerTypeInfo *typeInfo = layerType_getInfo(type);
1957
1958         if(!dest) return;
1959
1960         if(typeInfo->copy)
1961                 typeInfo->copy(source, dest, 1);
1962         else
1963                 memcpy(dest, source, typeInfo->size);
1964 }
1965
1966 void CustomData_em_interp(CustomData *data, void **src_blocks, float *weights,
1967                                                   float *sub_weights, int count, void *dest_block)
1968 {
1969         int i, j;
1970         void *source_buf[SOURCE_BUF_SIZE];
1971         void **sources = source_buf;
1972
1973         /* slow fallback in case we're interpolating a ridiculous number of
1974          * elements
1975          */
1976         if(count > SOURCE_BUF_SIZE)
1977                 sources = MEM_callocN(sizeof(*sources) * count,
1978                                                           "CustomData_interp sources");
1979
1980         /* interpolates a layer at a time */
1981         for(i = 0; i < data->totlayer; ++i) {
1982                 CustomDataLayer *layer = &data->layers[i];
1983                 const LayerTypeInfo *typeInfo = layerType_getInfo(layer->type);
1984
1985                 if(typeInfo->interp) {
1986                         for(j = 0; j < count; ++j)
1987                                 sources[j] = (char *)src_blocks[j] + layer->offset;
1988
1989                         typeInfo->interp(sources, weights, sub_weights, count,
1990                                                           (char *)dest_block + layer->offset);
1991                 }
1992         }
1993
1994         if(count > SOURCE_BUF_SIZE) MEM_freeN(sources);
1995 }
1996
1997 void CustomData_em_set_default(CustomData *data, void **block)
1998 {
1999         const LayerTypeInfo *typeInfo;
2000         int i;
2001
2002         if (!*block)
2003                 CustomData_em_alloc_block(data, block);
2004
2005         for(i = 0; i < data->totlayer; ++i) {
2006                 int offset = data->layers[i].offset;
2007
2008                 typeInfo = layerType_getInfo(data->layers[i].type);
2009
2010                 if(typeInfo->set_default)
2011                         typeInfo->set_default((char*)*block + offset, 1);
2012         }
2013 }
2014
2015 void CustomData_to_em_block(const CustomData *source, CustomData *dest,
2016                                                         int src_index, void **dest_block)
2017 {
2018         const LayerTypeInfo *typeInfo;
2019         int dest_i, src_i, src_offset;
2020
2021         if (!*dest_block)
2022                 CustomData_em_alloc_block(dest, dest_block);
2023         
2024         /* copies a layer at a time */
2025         dest_i = 0;
2026         for(src_i = 0; src_i < source->totlayer; ++src_i) {
2027
2028                 /* find the first dest layer with type >= the source type
2029                  * (this should work because layers are ordered by type)
2030                  */
2031                 while(dest_i < dest->totlayer
2032                           && dest->layers[dest_i].type < source->layers[src_i].type)
2033                         ++dest_i;
2034
2035                 /* if there are no more dest layers, we're done */
2036                 if(dest_i >= dest->totlayer) return;
2037
2038                 /* if we found a matching layer, copy the data */
2039                 if(dest->layers[dest_i].type == source->layers[src_i].type) {
2040                         int offset = dest->layers[dest_i].offset;
2041                         char *src_data = source->layers[src_i].data;
2042                         char *dest_data = (char*)*dest_block + offset;
2043
2044                         typeInfo = layerType_getInfo(dest->layers[dest_i].type);
2045                         src_offset = src_index * typeInfo->size;
2046
2047                         if(typeInfo->copy)
2048                                 typeInfo->copy(src_data + src_offset, dest_data, 1);
2049                         else
2050                                 memcpy(dest_data, src_data + src_offset, typeInfo->size);
2051
2052                         /* if there are multiple source & dest layers of the same type,
2053                          * we don't want to copy all source layers to the same dest, so
2054                          * increment dest_i
2055                          */
2056                         ++dest_i;
2057                 }
2058         }
2059 }
2060
2061 void CustomData_from_em_block(const CustomData *source, CustomData *dest,
2062                                                           void *src_block, int dest_index)
2063 {
2064         const LayerTypeInfo *typeInfo;
2065         int dest_i, src_i, dest_offset;
2066
2067         /* copies a layer at a time */
2068         dest_i = 0;
2069         for(src_i = 0; src_i < source->totlayer; ++src_i) {
2070
2071                 /* find the first dest layer with type >= the source type
2072                  * (this should work because layers are ordered by type)
2073                  */
2074                 while(dest_i < dest->totlayer
2075                           && dest->layers[dest_i].type < source->layers[src_i].type)
2076                         ++dest_i;
2077
2078                 /* if there are no more dest layers, we're done */
2079                 if(dest_i >= dest->totlayer) return;
2080
2081                 /* if we found a matching layer, copy the data */
2082                 if(dest->layers[dest_i].type == source->layers[src_i].type) {
2083                         int offset = source->layers[src_i].offset;
2084                         char *src_data = (char*)src_block + offset;
2085                         char *dest_data = dest->layers[dest_i].data;
2086
2087                         typeInfo = layerType_getInfo(dest->layers[dest_i].type);
2088                         dest_offset = dest_index * typeInfo->size;
2089
2090                         if(typeInfo->copy)
2091                                 typeInfo->copy(src_data, dest_data + dest_offset, 1);
2092                         else
2093                                 memcpy(dest_data + dest_offset, src_data, typeInfo->size);
2094
2095                         /* if there are multiple source & dest layers of the same type,
2096                          * we don't want to copy all source layers to the same dest, so
2097                          * increment dest_i
2098                          */
2099                         ++dest_i;
2100                 }
2101         }
2102
2103 }
2104
2105 /*Bmesh functions*/
2106 /*needed to convert to/from different face reps*/
2107 void CustomData_to_bmeshpoly(CustomData *fdata, CustomData *pdata, CustomData *ldata)
2108 {
2109         int i;
2110         for(i=0; i < fdata->totlayer; i++){
2111                 if(fdata->layers[i].type == CD_MTFACE){
2112                         CustomData_add_layer(pdata, CD_MTEXPOLY, CD_CALLOC, &(fdata->layers[i].name), 0);
2113                         CustomData_add_layer(ldata, CD_MLOOPUV, CD_CALLOC, &(fdata->layers[i].name), 0);
2114                 }
2115                 else if(fdata->layers[i].type == CD_MCOL)
2116                         CustomData_add_layer(ldata, CD_MLOOPCOL, CD_CALLOC, &(fdata->layers[i].name), 0);
2117         }               
2118 }
2119 void CustomData_from_bmeshpoly(CustomData *fdata, CustomData *pdata, CustomData *ldata, int total)
2120 {
2121         int i;
2122         for(i=0; i < pdata->totlayer; i++){
2123                 if(pdata->layers[i].type == CD_MTEXPOLY)
2124                         CustomData_add_layer(fdata, CD_MTFACE, CD_CALLOC, &(pdata->layers[i].name), total);
2125         }
2126         for(i=0; i < ldata->totlayer; i++){
2127                 if(ldata->layers[i].type == CD_MLOOPCOL)
2128                         CustomData_add_layer(fdata, CD_MCOL, CD_CALLOC, &(ldata->layers[i].name), total);
2129         }
2130 }
2131
2132
2133 void CustomData_bmesh_init_pool(CustomData *data, int allocsize)
2134 {
2135         if(data->totlayer)data->pool = BLI_mempool_create(data->totsize, allocsize, allocsize, FALSE, FALSE);
2136 }
2137
2138 void CustomData_bmesh_free_block(CustomData *data, void **block)
2139 {
2140         const LayerTypeInfo *typeInfo;
2141         int i;
2142
2143         if(!*block) return;
2144         for(i = 0; i < data->totlayer; ++i) {
2145                 if(!(data->layers[i].flag & CD_FLAG_NOFREE)) {
2146                         typeInfo = layerType_getInfo(data->layers[i].type);
2147
2148                         if(typeInfo->free) {
2149                                 int offset = data->layers[i].offset;
2150                                 typeInfo->free((char*)*block + offset, 1, typeInfo->size);
2151                         }
2152                 }
2153         }
2154
2155         BLI_mempool_free(data->pool, *block);
2156         *block = NULL;
2157 }
2158
2159 static void CustomData_bmesh_alloc_block(CustomData *data, void **block)
2160 {
2161
2162         if (*block)
2163                 CustomData_bmesh_free_block(data, block);
2164
2165         if (data->totsize > 0)
2166                 *block = BLI_mempool_calloc(data->pool);
2167         else
2168                 *block = NULL;
2169 }
2170
2171 void CustomData_bmesh_copy_data(const CustomData *source, CustomData *dest,
2172                                                         void *src_block, void **dest_block)
2173 {
2174         const LayerTypeInfo *typeInfo;
2175         int dest_i, src_i;
2176
2177         if (!*dest_block)
2178                 CustomData_bmesh_alloc_block(dest, dest_block);
2179         
2180         /* copies a layer at a time */
2181         dest_i = 0;
2182         for(src_i = 0; src_i < source->totlayer; ++src_i) {
2183
2184                 /* find the first dest layer with type >= the source type
2185                  * (this should work because layers are ordered by type)
2186                  */
2187                 while(dest_i < dest->totlayer
2188                           && dest->layers[dest_i].type < source->layers[src_i].type)
2189                         ++dest_i;
2190
2191                 /* if there are no more dest layers, we're done */
2192                 if(dest_i >= dest->totlayer) return;
2193
2194                 /* if we found a matching layer, copy the data */
2195                 if(dest->layers[dest_i].type == source->layers[src_i].type &&
2196                         strcmp(dest->layers[dest_i].name, source->layers[src_i].name) == 0) {
2197                         char *src_data = (char*)src_block + source->layers[src_i].offset;
2198                         char *dest_data = (char*)*dest_block + dest->layers[dest_i].offset;
2199
2200                         typeInfo = layerType_getInfo(source->layers[src_i].type);
2201
2202                         if(typeInfo->copy)
2203                                 typeInfo->copy(src_data, dest_data, 1);
2204                         else
2205                                 memcpy(dest_data, src_data, typeInfo->size);
2206
2207                         /* if there are multiple source & dest layers of the same type,
2208                          * we don't want to copy all source layers to the same dest, so
2209                          * increment dest_i
2210                          */
2211                         ++dest_i;
2212                 }
2213         }
2214 }
2215
2216 /*Bmesh Custom Data Functions. Should replace editmesh ones with these as well, due to more effecient memory alloc*/
2217 void *CustomData_bmesh_get(const CustomData *data, void *block, int type)
2218 {
2219         int layer_index;
2220         
2221         /* get the layer index of the first layer of type */
2222         layer_index = CustomData_get_active_layer_index(data, type);
2223         if(layer_index < 0) return NULL;
2224
2225         return (char *)block + data->layers[layer_index].offset;
2226 }
2227
2228 void *CustomData_bmesh_get_n(const CustomData *data, void *block, int type, int n)
2229 {
2230         int layer_index;
2231         
2232         /* get the layer index of the first layer of type */
2233         layer_index = CustomData_get_layer_index(data, type);
2234         if(layer_index < 0) return NULL;
2235
2236         return (char *)block + data->layers[layer_index+n].offset;
2237 }
2238
2239 /*gets from the layer at physical index n, note: doesn't check type.*/
2240 void *CustomData_bmesh_get_layer_n(const CustomData *data, void *block, int n)
2241 {
2242         if(n < 0 || n >= data->totlayer) return NULL;
2243
2244         return (char *)block + data->layers[n].offset;
2245 }
2246
2247
2248 void CustomData_bmesh_set(const CustomData *data, void *block, int type, void *source)
2249 {
2250         void *dest = CustomData_bmesh_get(data, block, type);
2251         const LayerTypeInfo *typeInfo = layerType_getInfo(type);
2252
2253         if(!dest) return;
2254
2255         if(typeInfo->copy)
2256                 typeInfo->copy(source, dest, 1);
2257         else
2258                 memcpy(dest, source, typeInfo->size);
2259 }
2260
2261 void CustomData_bmesh_set_n(CustomData *data, void *block, int type, int n, void *source)
2262 {
2263         void *dest = CustomData_bmesh_get_n(data, block, type, n);
2264         const LayerTypeInfo *typeInfo = layerType_getInfo(type);
2265
2266         if(!dest) return;
2267
2268         if(typeInfo->copy)
2269                 typeInfo->copy(source, dest, 1);
2270         else
2271                 memcpy(dest, source, typeInfo->size);
2272 }
2273
2274 void CustomData_bmesh_set_layer_n(CustomData *data, void *block, int n, void *source)
2275 {
2276         void *dest = CustomData_bmesh_get_layer_n(data, block, n);
2277         const LayerTypeInfo *typeInfo = layerType_getInfo(data->layers[n].type);
2278
2279         if(!dest) return;
2280
2281         if(typeInfo->copy)
2282                 typeInfo->copy(source, dest, 1);
2283         else
2284                 memcpy(dest, source, typeInfo->size);
2285 }
2286
2287 void CustomData_bmesh_interp(CustomData *data, void **src_blocks, float *weights,
2288                                                   float *sub_weights, int count, void *dest_block)
2289 {
2290         int i, j;
2291         void *source_buf[SOURCE_BUF_SIZE];
2292         void **sources = source_buf;
2293
2294         /* slow fallback in case we're interpolating a ridiculous number of
2295          * elements
2296          */
2297         if(count > SOURCE_BUF_SIZE)
2298                 sources = MEM_callocN(sizeof(*sources) * count,
2299                                                           "CustomData_interp sources");
2300
2301         /* interpolates a layer at a time */
2302         for(i = 0; i < data->totlayer; ++i) {
2303                 CustomDataLayer *layer = &data->layers[i];
2304                 const LayerTypeInfo *typeInfo = layerType_getInfo(layer->type);
2305                 if(typeInfo->interp) {
2306                         for(j = 0; j < count; ++j)
2307                                 sources[j] = (char *)src_blocks[j] + layer->offset;
2308
2309                         typeInfo->interp(sources, weights, sub_weights, count,
2310                                                           (char *)dest_block + layer->offset);
2311                 }
2312         }
2313
2314         if(count > SOURCE_BUF_SIZE) MEM_freeN(sources);
2315 }
2316
2317 void CustomData_bmesh_set_default(CustomData *data, void **block)
2318 {
2319         const LayerTypeInfo *typeInfo;
2320         int i;
2321
2322         if (!*block)
2323                 CustomData_bmesh_alloc_block(data, block);
2324
2325         for(i = 0; i < data->totlayer; ++i) {
2326                 int offset = data->layers[i].offset;
2327
2328                 typeInfo = layerType_getInfo(data->layers[i].type);
2329
2330                 if(typeInfo->set_default)
2331                         typeInfo->set_default((char*)*block + offset, 1);
2332                 else memset((char*)*block + offset, 0, typeInfo->size);
2333         }
2334 }
2335
2336 void CustomData_to_bmesh_block(const CustomData *source, CustomData *dest,
2337                                                         int src_index, void **dest_block)
2338 {
2339         const LayerTypeInfo *typeInfo;
2340         int dest_i, src_i, src_offset;
2341
2342         if (!*dest_block)
2343                 CustomData_bmesh_alloc_block(dest, dest_block);
2344         
2345         /* copies a layer at a time */
2346         dest_i = 0;
2347         for(src_i = 0; src_i < source->totlayer; ++src_i) {
2348
2349                 /* find the first dest layer with type >= the source type
2350                  * (this should work because layers are ordered by type)
2351                  */
2352                 while(dest_i < dest->totlayer
2353                           && dest->layers[dest_i].type < source->layers[src_i].type)
2354                         ++dest_i;
2355
2356                 /* if there are no more dest layers, we're done */
2357                 if(dest_i >= dest->totlayer) return;
2358
2359                 /* if we found a matching layer, copy the data */
2360                 if(dest->layers[dest_i].type == source->layers[src_i].type) {
2361                         int offset = dest->layers[dest_i].offset;
2362                         char *src_data = source->layers[src_i].data;
2363                         char *dest_data = (char*)*dest_block + offset;
2364
2365                         typeInfo = layerType_getInfo(dest->layers[dest_i].type);
2366                         src_offset = src_index * typeInfo->size;
2367
2368                         if(typeInfo->copy)
2369                                 typeInfo->copy(src_data + src_offset, dest_data, 1);
2370                         else
2371                                 memcpy(dest_data, src_data + src_offset, typeInfo->size);
2372
2373                         /* if there are multiple source & dest layers of the same type,
2374                          * we don't want to copy all source layers to the same dest, so
2375                          * increment dest_i
2376                          */
2377                         ++dest_i;
2378                 }
2379         }
2380 }
2381
2382 void CustomData_from_bmesh_block(const CustomData *source, CustomData *dest,
2383                                                           void *src_block, int dest_index)
2384 {
2385         const LayerTypeInfo *typeInfo;
2386         int dest_i, src_i, dest_offset;
2387
2388         /* copies a layer at a time */
2389         dest_i = 0;
2390         for(src_i = 0; src_i < source->totlayer; ++src_i) {
2391
2392                 /* find the first dest layer with type >= the source type
2393                  * (this should work because layers are ordered by type)
2394                  */
2395                 while(dest_i < dest->totlayer
2396                           && dest->layers[dest_i].type < source->layers[src_i].type)
2397                         ++dest_i;
2398
2399                 /* if there are no more dest layers, we're done */
2400                 if(dest_i >= dest->totlayer) return;
2401
2402                 /* if we found a matching layer, copy the data */
2403                 if(dest->layers[dest_i].type == source->layers[src_i].type) {
2404                         int offset = source->layers[src_i].offset;
2405                         char *src_data = (char*)src_block + offset;
2406                         char *dest_data = dest->layers[dest_i].data;
2407
2408                         typeInfo = layerType_getInfo(dest->layers[dest_i].type);
2409                         dest_offset = dest_index * typeInfo->size;
2410
2411                         if(typeInfo->copy)
2412                                 typeInfo->copy(src_data, dest_data + dest_offset, 1);
2413                         else
2414                                 memcpy(dest_data + dest_offset, src_data, typeInfo->size);
2415
2416                         /* if there are multiple source & dest layers of the same type,
2417                          * we don't want to copy all source layers to the same dest, so
2418                          * increment dest_i
2419                          */
2420                         ++dest_i;
2421                 }
2422         }
2423
2424 }
2425
2426 void CustomData_file_write_info(int type, const char **structname, int *structnum)
2427 {
2428         const LayerTypeInfo *typeInfo = layerType_getInfo(type);
2429
2430         *structname = typeInfo->structname;
2431         *structnum = typeInfo->structnum;
2432 }
2433
2434 int CustomData_sizeof(int type)
2435 {
2436         const LayerTypeInfo *typeInfo = layerType_getInfo(type);
2437
2438         return typeInfo->size;
2439 }
2440
2441 const char *CustomData_layertype_name(int type)
2442 {
2443         return layerType_getName(type);
2444 }
2445
2446 static int  CustomData_is_property_layer(int type)
2447 {
2448         if((type == CD_PROP_FLT) || (type == CD_PROP_INT) || (type == CD_PROP_STR))
2449                 return 1;
2450         return 0;
2451 }
2452
2453 static int cd_layer_find_dupe(CustomData *data, const char *name, int type, int index)
2454 {
2455         int i;
2456         /* see if there is a duplicate */
2457         for(i=0; i<data->totlayer; i++) {
2458                 if(i != index) {
2459                         CustomDataLayer *layer= &data->layers[i];
2460                         
2461                         if(CustomData_is_property_layer(type)) {
2462                                 if(CustomData_is_property_layer(layer->type) && strcmp(layer->name, name)==0) {
2463                                         return 1;
2464                                 }
2465                         }
2466                         else{
2467                                 if(i!=index && layer->type==type && strcmp(layer->name, name)==0) {
2468                                         return 1;
2469                                 }
2470                         }
2471                 }
2472         }
2473         
2474         return 0;
2475 }
2476
2477 static int customdata_unique_check(void *arg, const char *name)
2478 {
2479         struct {CustomData *data; int type; int index;} *data_arg= arg;
2480         return cd_layer_find_dupe(data_arg->data, name, data_arg->type, data_arg->index);
2481 }
2482
2483 void CustomData_set_layer_unique_name(CustomData *data, int index)
2484 {       
2485         CustomDataLayer *nlayer= &data->layers[index];
2486         const LayerTypeInfo *typeInfo= layerType_getInfo(nlayer->type);
2487
2488         struct {CustomData *data; int type; int index;} data_arg;
2489         data_arg.data= data;
2490         data_arg.type= nlayer->type;
2491         data_arg.index= index;
2492
2493         if (!typeInfo->defaultname)
2494                 return;
2495         
2496         BLI_uniquename_cb(customdata_unique_check, &data_arg, typeInfo->defaultname, '.', nlayer->name, sizeof(nlayer->name));
2497 }
2498
2499 void CustomData_validate_layer_name(const CustomData *data, int type, char *name, char *outname)
2500 {
2501         int index = -1;
2502
2503         /* if a layer name was given, try to find that layer */
2504         if(name[0])
2505                 index = CustomData_get_named_layer_index(data, type, name);
2506
2507         if(index < 0) {
2508                 /* either no layer was specified, or the layer we want has been
2509                 * deleted, so assign the active layer to name
2510                 */
2511                 index = CustomData_get_active_layer_index(data, type);
2512                 strcpy(outname, data->layers[index].name);
2513         }
2514         else
2515                 strcpy(outname, name);
2516 }
2517
2518 int CustomData_verify_versions(struct CustomData *data, int index)
2519 {
2520         const LayerTypeInfo *typeInfo;
2521         CustomDataLayer *layer = &data->layers[index];
2522         int i, keeplayer = 1;
2523
2524         if (layer->type >= CD_NUMTYPES) {
2525                 keeplayer = 0; /* unknown layer type from future version */
2526         }
2527         else {
2528                 typeInfo = layerType_getInfo(layer->type);
2529
2530                 if (!typeInfo->defaultname && (index > 0) &&
2531                         data->layers[index-1].type == layer->type)
2532                         keeplayer = 0; /* multiple layers of which we only support one */
2533         }
2534
2535         if (!keeplayer) {
2536                 for (i=index+1; i < data->totlayer; ++i)
2537                         data->layers[i-1] = data->layers[i];
2538                 data->totlayer--;
2539         }
2540
2541         return keeplayer;
2542 }
2543
2544 /****************************** External Files *******************************/
2545
2546 static void customdata_external_filename(char filename[FILE_MAX], ID *id, CustomDataExternal *external)
2547 {
2548         BLI_strncpy(filename, external->filename, FILE_MAX);
2549         BLI_path_abs(filename, ID_BLEND_PATH(G.main, id));
2550 }
2551
2552 void CustomData_external_reload(CustomData *data, ID *UNUSED(id), CustomDataMask mask, int totelem)
2553 {
2554         CustomDataLayer *layer;
2555         const LayerTypeInfo *typeInfo;
2556         int i;
2557
2558         for(i=0; i<data->totlayer; i++) {
2559                 layer = &data->layers[i];
2560                 typeInfo = layerType_getInfo(layer->type);
2561
2562                 if(!(mask & CD_TYPE_AS_MASK(layer->type)));
2563                 else if((layer->flag & CD_FLAG_EXTERNAL) && (layer->flag & CD_FLAG_IN_MEMORY)) {
2564                         if(typeInfo->free)
2565                                 typeInfo->free(layer->data, totelem, typeInfo->size);
2566                         layer->flag &= ~CD_FLAG_IN_MEMORY;
2567                 }
2568         }
2569 }
2570
2571 void CustomData_external_read(CustomData *data, ID *id, CustomDataMask mask, int totelem)
2572 {
2573         CustomDataExternal *external= data->external;
2574         CustomDataLayer *layer;
2575         CDataFile *cdf;
2576         CDataFileLayer *blay;
2577         char filename[FILE_MAX];
2578         const LayerTypeInfo *typeInfo;
2579         int i, update = 0;
2580
2581         if(!external)
2582                 return;
2583         
2584         for(i=0; i<data->totlayer; i++) {
2585                 layer = &data->layers[i];
2586                 typeInfo = layerType_getInfo(layer->type);
2587
2588                 if(!(mask & CD_TYPE_AS_MASK(layer->type)));
2589                 else if(layer->flag & CD_FLAG_IN_MEMORY);
2590                 else if((layer->flag & CD_FLAG_EXTERNAL) && typeInfo->read)
2591                         update= 1;
2592         }
2593
2594         if(!update)
2595                 return;
2596
2597         customdata_external_filename(filename, id, external);
2598
2599         cdf= cdf_create(CDF_TYPE_MESH);
2600         if(!cdf_read_open(cdf, filename)) {
2601                 fprintf(stderr, "Failed to read %s layer from %s.\n", layerType_getName(layer->type), filename);
2602                 return;
2603         }
2604
2605         for(i=0; i<data->totlayer; i++) {
2606                 layer = &data->layers[i];
2607                 typeInfo = layerType_getInfo(layer->type);
2608
2609                 if(!(mask & CD_TYPE_AS_MASK(layer->type)));
2610                 else if(layer->flag & CD_FLAG_IN_MEMORY);
2611                 else if((layer->flag & CD_FLAG_EXTERNAL) && typeInfo->read) {
2612                         blay= cdf_layer_find(cdf, layer->type, layer->name);
2613
2614                         if(blay) {
2615                                 if(cdf_read_layer(cdf, blay)) {
2616                                         if(typeInfo->read(cdf, layer->data, totelem));
2617                                         else break;
2618                                         layer->flag |= CD_FLAG_IN_MEMORY;
2619                                 }
2620                                 else
2621                                         break;
2622                         }
2623                 }
2624         }
2625
2626         cdf_read_close(cdf);
2627         cdf_free(cdf);
2628 }
2629
2630 void CustomData_external_write(CustomData *data, ID *id, CustomDataMask mask, int totelem, int free)
2631 {
2632         CustomDataExternal *external= data->external;
2633         CustomDataLayer *layer;
2634         CDataFile *cdf;
2635         CDataFileLayer *blay;
2636         const LayerTypeInfo *typeInfo;
2637         int i, update = 0;
2638         char filename[FILE_MAX];
2639
2640         if(!external)
2641                 return;
2642
2643         /* test if there is anything to write */
2644         for(i=0; i<data->totlayer; i++) {
2645                 layer = &data->layers[i];
2646                 typeInfo = layerType_getInfo(layer->type);
2647
2648                 if(!(mask & CD_TYPE_AS_MASK(layer->type)));
2649                 else if((layer->flag & CD_FLAG_EXTERNAL) && typeInfo->write)
2650                         update= 1;
2651         }
2652
2653         if(!update)
2654                 return;
2655
2656         /* make sure data is read before we try to write */
2657         CustomData_external_read(data, id, mask, totelem);
2658         customdata_external_filename(filename, id, external);
2659
2660         cdf= cdf_create(CDF_TYPE_MESH);
2661
2662         for(i=0; i<data->totlayer; i++) {
2663                 layer = &data->layers[i];
2664                 typeInfo = layerType_getInfo(layer->type);
2665
2666                 if((layer->flag & CD_FLAG_EXTERNAL) && typeInfo->filesize) {
2667                         if(layer->flag & CD_FLAG_IN_MEMORY) {
2668                                 cdf_layer_add(cdf, layer->type, layer->name,
2669                                         typeInfo->filesize(cdf, layer->data, totelem));
2670                         }
2671                         else {
2672                                 cdf_free(cdf);
2673                                 return; /* read failed for a layer! */
2674                         }
2675                 }
2676         }
2677
2678         if(!cdf_write_open(cdf, filename)) {
2679                 fprintf(stderr, "Failed to open %s for writing.\n", filename);
2680                 return;
2681         }
2682
2683         for(i=0; i<data->totlayer; i++) {
2684                 layer = &data->layers[i];
2685                 typeInfo = layerType_getInfo(layer->type);
2686
2687                 if((layer->flag & CD_FLAG_EXTERNAL) && typeInfo->write) {
2688                         blay= cdf_layer_find(cdf, layer->type, layer->name);
2689
2690                         if(cdf_write_layer(cdf, blay)) {
2691                                 if(typeInfo->write(cdf, layer->data, totelem));
2692                                 else break;
2693                         }
2694                         else
2695                                 break;
2696                 }
2697         }
2698
2699         if(i != data->totlayer) {
2700                 fprintf(stderr, "Failed to write data to %s.\n", filename);
2701                 cdf_free(cdf);
2702                 return;
2703         }
2704
2705         for(i=0; i<data->totlayer; i++) {
2706                 layer = &data->layers[i];
2707                 typeInfo = layerType_getInfo(layer->type);
2708
2709                 if((layer->flag & CD_FLAG_EXTERNAL) && typeInfo->write) {
2710                         if(free) {
2711                                 if(typeInfo->free)
2712                                         typeInfo->free(layer->data, totelem, typeInfo->size);
2713                                 layer->flag &= ~CD_FLAG_IN_MEMORY;
2714                         }
2715                 }
2716         }
2717
2718         cdf_write_close(cdf);
2719         cdf_free(cdf);
2720 }
2721
2722 void CustomData_external_add(CustomData *data, ID *UNUSED(id), int type, int UNUSED(totelem), const char *filename)
2723 {
2724         CustomDataExternal *external= data->external;
2725         CustomDataLayer *layer;
2726         int layer_index;
2727
2728         layer_index = CustomData_get_active_layer_index(data, type);
2729         if(layer_index < 0) return;
2730
2731         layer = &data->layers[layer_index];
2732
2733         if(layer->flag & CD_FLAG_EXTERNAL)
2734                 return;
2735
2736         if(!external) {
2737                 external= MEM_callocN(sizeof(CustomDataExternal), "CustomDataExternal");
2738                 data->external= external;
2739         }
2740         BLI_strncpy(external->filename, filename, sizeof(external->filename));
2741
2742         layer->flag |= CD_FLAG_EXTERNAL|CD_FLAG_IN_MEMORY;
2743 }
2744
2745 void CustomData_external_remove(CustomData *data, ID *id, int type, int totelem)
2746 {
2747         CustomDataExternal *external= data->external;
2748         CustomDataLayer *layer;
2749         //char filename[FILE_MAX];
2750         int layer_index; // i, remove_file;
2751
2752         layer_index = CustomData_get_active_layer_index(data, type);
2753         if(layer_index < 0) return;
2754
2755         layer = &data->layers[layer_index];
2756
2757         if(!external)
2758                 return;
2759
2760         if(layer->flag & CD_FLAG_EXTERNAL) {
2761                 if(!(layer->flag & CD_FLAG_IN_MEMORY))
2762                         CustomData_external_read(data, id, CD_TYPE_AS_MASK(layer->type), totelem);
2763
2764                 layer->flag &= ~CD_FLAG_EXTERNAL;
2765
2766 #if 0
2767                 remove_file= 1;
2768                 for(i=0; i<data->totlayer; i++)
2769                         if(data->layers[i].flag & CD_FLAG_EXTERNAL)
2770                                 remove_file= 0;
2771
2772                 if(remove_file) {
2773                         customdata_external_filename(filename, id, external);
2774                         cdf_remove(filename);
2775                         CustomData_external_free(data);
2776                 }
2777 #endif
2778         }
2779 }
2780
2781 int CustomData_external_test(CustomData *data, int type)
2782 {
2783         CustomDataLayer *layer;
2784         int layer_index;
2785
2786         layer_index = CustomData_get_active_layer_index(data, type);
2787         if(layer_index < 0) return 0;
2788
2789         layer = &data->layers[layer_index];
2790         return (layer->flag & CD_FLAG_EXTERNAL);
2791 }
2792
2793 #if 0
2794 void CustomData_external_remove_object(CustomData *data, ID *id)
2795 {
2796         CustomDataExternal *external= data->external;
2797         char filename[FILE_MAX];
2798
2799         if(!external)
2800                 return;
2801
2802         customdata_external_filename(filename, id, external);
2803         cdf_remove(filename);
2804         CustomData_external_free(data);
2805 }
2806 #endif
2807