0363ba459a701a2a8455c82d696c4664bb94d202
[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_FLAGS */
833         {sizeof(int), "", 0, 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
900 static const LayerTypeInfo *layerType_getInfo(int type)
901 {
902         if(type < 0 || type >= CD_NUMTYPES) return NULL;
903
904         return &LAYERTYPEINFO[type];
905 }
906
907 static const char *layerType_getName(int type)
908 {
909         if(type < 0 || type >= CD_NUMTYPES) return NULL;
910
911         return LAYERTYPENAMES[type];
912 }
913
914 /********************* CustomData functions *********************/
915 static void customData_update_offsets(CustomData *data);
916
917 static CustomDataLayer *customData_add_layer__internal(CustomData *data,
918         int type, int alloctype, void *layerdata, int totelem, const char *name);
919
920 void CustomData_update_typemap(CustomData *data)
921 {
922         int i, lasttype = -1;
923
924         /* since we cant do in a pre-processor do here as an assert */
925         BLI_assert(sizeof(data->typemap) / sizeof(int) >= CD_NUMTYPES);
926
927         for (i=0; i<CD_NUMTYPES; i++) {
928                 data->typemap[i] = -1;
929         }
930
931         for (i=0; i<data->totlayer; i++) {
932                 if (data->layers[i].type != lasttype) {
933                         data->typemap[data->layers[i].type] = i;
934                 }
935                 lasttype = data->layers[i].type;
936         }
937 }
938
939 void CustomData_merge(const struct CustomData *source, struct CustomData *dest,
940                                           CustomDataMask mask, int alloctype, int totelem)
941 {
942         /*const LayerTypeInfo *typeInfo;*/
943         CustomDataLayer *layer, *newlayer;
944         int i, type, number = 0, lasttype = -1, lastactive = 0, lastrender = 0, lastclone = 0, lastmask = 0, lastflag = 0;
945
946         for(i = 0; i < source->totlayer; ++i) {
947                 layer = &source->layers[i];
948                 /*typeInfo = layerType_getInfo(layer->type);*/ /*UNUSED*/
949
950                 type = layer->type;
951
952                 if (type != lasttype) {
953                         number = 0;
954                         lastactive = layer->active;
955                         lastrender = layer->active_rnd;
956                         lastclone = layer->active_clone;
957                         lastmask = layer->active_mask;
958                         lasttype = type;
959                         lastflag = layer->flag;
960                 }
961                 else
962                         number++;
963
964                 if(lastflag & CD_FLAG_NOCOPY) continue;
965                 else if(!(mask & CD_TYPE_AS_MASK(type))) continue;
966                 else if(number < CustomData_number_of_layers(dest, type)) continue;
967
968                 if((alloctype == CD_ASSIGN) && (lastflag & CD_FLAG_NOFREE))
969                         newlayer = customData_add_layer__internal(dest, type, CD_REFERENCE,
970                                 layer->data, totelem, layer->name);
971                 else
972                         newlayer = customData_add_layer__internal(dest, type, alloctype,
973                                 layer->data, totelem, layer->name);
974                 
975                 if(newlayer) {
976                         newlayer->active = lastactive;
977                         newlayer->active_rnd = lastrender;
978                         newlayer->active_clone = lastclone;
979                         newlayer->active_mask = lastmask;
980                         newlayer->flag |= lastflag & (CD_FLAG_EXTERNAL|CD_FLAG_IN_MEMORY);
981                 }
982         }
983
984         CustomData_update_typemap(dest);
985 }
986
987 void CustomData_copy(const struct CustomData *source, struct CustomData *dest,
988                                          CustomDataMask mask, int alloctype, int totelem)
989 {
990         memset(dest, 0, sizeof(*dest));
991
992         if(source->external)
993                 dest->external= MEM_dupallocN(source->external);
994
995         CustomData_merge(source, dest, mask, alloctype, totelem);
996 }
997
998 static void customData_free_layer__internal(CustomDataLayer *layer, int totelem)
999 {
1000         const LayerTypeInfo *typeInfo;
1001
1002         if(!(layer->flag & CD_FLAG_NOFREE) && layer->data) {
1003                 typeInfo = layerType_getInfo(layer->type);
1004
1005                 if(typeInfo->free)
1006                         typeInfo->free(layer->data, totelem, typeInfo->size);
1007
1008                 if(layer->data)
1009                         MEM_freeN(layer->data);
1010         }
1011 }
1012
1013 static void CustomData_external_free(CustomData *data)
1014 {
1015         if(data->external) {
1016                 MEM_freeN(data->external);
1017                 data->external= NULL;
1018         }
1019 }
1020
1021 void CustomData_free(CustomData *data, int totelem)
1022 {
1023         int i;
1024
1025         for(i = 0; i < data->totlayer; ++i)
1026                 customData_free_layer__internal(&data->layers[i], totelem);
1027
1028         if(data->layers)
1029                 MEM_freeN(data->layers);
1030         
1031         CustomData_external_free(data);
1032         
1033         memset(data, 0, sizeof(*data));
1034 }
1035
1036 static void customData_update_offsets(CustomData *data)
1037 {
1038         const LayerTypeInfo *typeInfo;
1039         int i, offset = 0;
1040
1041         for(i = 0; i < data->totlayer; ++i) {
1042                 typeInfo = layerType_getInfo(data->layers[i].type);
1043
1044                 data->layers[i].offset = offset;
1045                 offset += typeInfo->size;
1046         }
1047
1048         data->totsize = offset;
1049         CustomData_update_typemap(data);
1050 }
1051
1052 int CustomData_get_layer_index(const CustomData *data, int type)
1053 {
1054         int i; 
1055
1056         for(i=0; i < data->totlayer; ++i)
1057                 if(data->layers[i].type == type)
1058                         return i;
1059
1060         return -1;
1061 }
1062
1063 int CustomData_get_layer_index_n(const struct CustomData *data, int type, int n)
1064 {
1065         int i = CustomData_get_layer_index(data, type);
1066
1067         if (i != -1) {
1068                 i = (data->layers[i + n].type == type) ? (i + n) : (-1);
1069         }
1070
1071         return i;
1072 }
1073
1074 int CustomData_get_named_layer_index(const CustomData *data, int type, const char *name)
1075 {
1076         int i;
1077
1078         for(i=0; i < data->totlayer; ++i)
1079                 if(data->layers[i].type == type && strcmp(data->layers[i].name, name)==0)
1080                         return i;
1081
1082         return -1;
1083 }
1084
1085 int CustomData_get_active_layer_index(const CustomData *data, int type)
1086 {
1087         if (!data->totlayer)
1088                 return -1;
1089
1090         if (data->typemap[type] != -1) {
1091                 return data->typemap[type] + data->layers[data->typemap[type]].active;
1092         }
1093
1094         return -1;
1095 }
1096
1097 int CustomData_get_render_layer_index(const CustomData *data, int type)
1098 {
1099         int i;
1100
1101         for(i=0; i < data->totlayer; ++i)
1102                 if(data->layers[i].type == type)
1103                         return i + data->layers[i].active_rnd;
1104
1105         return -1;
1106 }
1107
1108 int CustomData_get_clone_layer_index(const CustomData *data, int type)
1109 {
1110         int i;
1111
1112         for(i=0; i < data->totlayer; ++i)
1113                 if(data->layers[i].type == type)
1114                         return i + data->layers[i].active_clone;
1115
1116         return -1;
1117 }
1118
1119 int CustomData_get_stencil_layer_index(const CustomData *data, int type)
1120 {
1121         int i;
1122
1123         for(i=0; i < data->totlayer; ++i)
1124                 if(data->layers[i].type == type)
1125                         return i + data->layers[i].active_mask;
1126
1127         return -1;
1128 }
1129
1130 int CustomData_get_active_layer(const CustomData *data, int type)
1131 {
1132         int i;
1133
1134         for(i=0; i < data->totlayer; ++i)
1135                 if(data->layers[i].type == type)
1136                         return data->layers[i].active;
1137
1138         return -1;
1139 }
1140
1141 int CustomData_get_render_layer(const CustomData *data, int type)
1142 {
1143         int i;
1144
1145         for(i=0; i < data->totlayer; ++i)
1146                 if(data->layers[i].type == type)
1147                         return data->layers[i].active_rnd;
1148
1149         return -1;
1150 }
1151
1152 int CustomData_get_clone_layer(const CustomData *data, int type)
1153 {
1154         int i;
1155
1156         for(i=0; i < data->totlayer; ++i)
1157                 if(data->layers[i].type == type)
1158                         return data->layers[i].active_clone;
1159
1160         return -1;
1161 }
1162
1163 int CustomData_get_stencil_layer(const CustomData *data, int type)
1164 {
1165         int i;
1166
1167         for(i=0; i < data->totlayer; ++i)
1168                 if(data->layers[i].type == type)
1169                         return data->layers[i].active_mask;
1170
1171         return -1;
1172 }
1173
1174 void CustomData_set_layer_active(CustomData *data, int type, int n)
1175 {
1176         int i;
1177
1178         for(i=0; i < data->totlayer; ++i)
1179                 if(data->layers[i].type == type)
1180                         data->layers[i].active = n;
1181 }
1182
1183 void CustomData_set_layer_render(CustomData *data, int type, int n)
1184 {
1185         int i;
1186
1187         for(i=0; i < data->totlayer; ++i)
1188                 if(data->layers[i].type == type)
1189                         data->layers[i].active_rnd = n;
1190 }
1191
1192 void CustomData_set_layer_clone(CustomData *data, int type, int n)
1193 {
1194         int i;
1195
1196         for(i=0; i < data->totlayer; ++i)
1197                 if(data->layers[i].type == type)
1198                         data->layers[i].active_clone = n;
1199 }
1200
1201 void CustomData_set_layer_stencil(CustomData *data, int type, int n)
1202 {
1203         int i;
1204
1205         for(i=0; i < data->totlayer; ++i)
1206                 if(data->layers[i].type == type)
1207                         data->layers[i].active_mask = n;
1208 }
1209
1210 /* for using with an index from CustomData_get_active_layer_index and CustomData_get_render_layer_index */
1211 void CustomData_set_layer_active_index(CustomData *data, int type, int n)
1212 {
1213         int i;
1214
1215         for(i=0; i < data->totlayer; ++i)
1216                 if(data->layers[i].type == type)
1217                         data->layers[i].active = n-i;
1218 }
1219
1220 void CustomData_set_layer_render_index(CustomData *data, int type, int n)
1221 {
1222         int i;
1223
1224         for(i=0; i < data->totlayer; ++i)
1225                 if(data->layers[i].type == type)
1226                         data->layers[i].active_rnd = n-i;
1227 }
1228
1229 void CustomData_set_layer_clone_index(CustomData *data, int type, int n)
1230 {
1231         int i;
1232
1233         for(i=0; i < data->totlayer; ++i)
1234                 if(data->layers[i].type == type)
1235                         data->layers[i].active_clone = n-i;
1236 }
1237
1238 void CustomData_set_layer_stencil_index(CustomData *data, int type, int n)
1239 {
1240         int i;
1241
1242         for(i=0; i < data->totlayer; ++i)
1243                 if(data->layers[i].type == type)
1244                         data->layers[i].active_mask = n-i;
1245 }
1246
1247 void CustomData_set_layer_flag(struct CustomData *data, int type, int flag)
1248 {
1249         int i;
1250
1251         for(i=0; i < data->totlayer; ++i)
1252                 if(data->layers[i].type == type)
1253                         data->layers[i].flag |= flag;
1254 }
1255
1256 static int customData_resize(CustomData *data, int amount)
1257 {
1258         CustomDataLayer *tmp = MEM_callocN(sizeof(*tmp)*(data->maxlayer + amount),
1259                                                                            "CustomData->layers");
1260         if(!tmp) return 0;
1261
1262         data->maxlayer += amount;
1263         if (data->layers) {
1264                 memcpy(tmp, data->layers, sizeof(*tmp) * data->totlayer);
1265                 MEM_freeN(data->layers);
1266         }
1267         data->layers = tmp;
1268
1269         return 1;
1270 }
1271
1272 static CustomDataLayer *customData_add_layer__internal(CustomData *data,
1273         int type, int alloctype, void *layerdata, int totelem, const char *name)
1274 {
1275         const LayerTypeInfo *typeInfo= layerType_getInfo(type);
1276         int size = typeInfo->size * totelem, flag = 0, index = data->totlayer;
1277         void *newlayerdata;
1278
1279         if (!typeInfo->defaultname && CustomData_has_layer(data, type))
1280                 return &data->layers[CustomData_get_layer_index(data, type)];
1281
1282         if((alloctype == CD_ASSIGN) || (alloctype == CD_REFERENCE)) {
1283                 newlayerdata = layerdata;
1284         }
1285         else {
1286                 newlayerdata = MEM_callocN(size, layerType_getName(type));
1287                 if(!newlayerdata)
1288                         return NULL;
1289         }
1290
1291         if (alloctype == CD_DUPLICATE) {
1292                 if(typeInfo->copy)
1293                         typeInfo->copy(layerdata, newlayerdata, totelem);
1294                 else
1295                         memcpy(newlayerdata, layerdata, size);
1296         }
1297         else if (alloctype == CD_DEFAULT) {
1298                 if(typeInfo->set_default)
1299                         typeInfo->set_default((char*)newlayerdata, totelem);
1300         }
1301         else if (alloctype == CD_REFERENCE)
1302                 flag |= CD_FLAG_NOFREE;
1303
1304         if(index >= data->maxlayer) {
1305                 if(!customData_resize(data, CUSTOMDATA_GROW)) {
1306                         if(newlayerdata != layerdata)
1307                                 MEM_freeN(newlayerdata);
1308                         return NULL;
1309                 }
1310         }
1311         
1312         data->totlayer++;
1313
1314         /* keep layers ordered by type */
1315         for( ; index > 0 && data->layers[index - 1].type > type; --index)
1316                 data->layers[index] = data->layers[index - 1];
1317
1318         data->layers[index].type = type;
1319         data->layers[index].flag = flag;
1320         data->layers[index].data = newlayerdata;
1321
1322         if(name || (name=typeInfo->defaultname)) {
1323                 BLI_strncpy(data->layers[index].name, name, 32);
1324                 CustomData_set_layer_unique_name(data, index);
1325         }
1326         else
1327                 data->layers[index].name[0] = '\0';
1328
1329         if(index > 0 && data->layers[index-1].type == type) {
1330                 data->layers[index].active = data->layers[index-1].active;
1331                 data->layers[index].active_rnd = data->layers[index-1].active_rnd;
1332                 data->layers[index].active_clone = data->layers[index-1].active_clone;
1333                 data->layers[index].active_mask = data->layers[index-1].active_mask;
1334         } else {
1335                 data->layers[index].active = 0;
1336                 data->layers[index].active_rnd = 0;
1337                 data->layers[index].active_clone = 0;
1338                 data->layers[index].active_mask = 0;
1339         }
1340         
1341         customData_update_offsets(data);
1342
1343         return &data->layers[index];
1344 }
1345
1346 void *CustomData_add_layer(CustomData *data, int type, int alloctype,
1347                                                    void *layerdata, int totelem)
1348 {
1349         CustomDataLayer *layer;
1350         const LayerTypeInfo *typeInfo= layerType_getInfo(type);
1351         
1352         layer = customData_add_layer__internal(data, type, alloctype, layerdata,
1353                                                                                    totelem, typeInfo->defaultname);
1354         CustomData_update_typemap(data);
1355
1356         if(layer)
1357                 return layer->data;
1358
1359         return NULL;
1360 }
1361
1362 /*same as above but accepts a name*/
1363 void *CustomData_add_layer_named(CustomData *data, int type, int alloctype,
1364                                                    void *layerdata, int totelem, const char *name)
1365 {
1366         CustomDataLayer *layer;
1367         
1368         layer = customData_add_layer__internal(data, type, alloctype, layerdata,
1369                                                                                    totelem, name);
1370         CustomData_update_typemap(data);
1371
1372         if(layer)
1373                 return layer->data;
1374
1375         return NULL;
1376 }
1377
1378
1379 int CustomData_free_layer(CustomData *data, int type, int totelem, int index)
1380 {
1381         int i;
1382         
1383         if (index < 0) return 0;
1384
1385         customData_free_layer__internal(&data->layers[index], totelem);
1386
1387         for (i=index+1; i < data->totlayer; ++i)
1388                 data->layers[i-1] = data->layers[i];
1389
1390         data->totlayer--;
1391
1392         /* if layer was last of type in array, set new active layer */
1393         if ((index >= data->totlayer) || (data->layers[index].type != type)) {
1394                 i = CustomData_get_layer_index(data, type);
1395                 
1396                 if (i >= 0)
1397                         for (; i < data->totlayer && data->layers[i].type == type; i++) {
1398                                 data->layers[i].active--;
1399                                 data->layers[i].active_rnd--;
1400                                 data->layers[i].active_clone--;
1401                                 data->layers[i].active_mask--;
1402                         }
1403         }
1404
1405         if (data->totlayer <= data->maxlayer-CUSTOMDATA_GROW)
1406                 customData_resize(data, -CUSTOMDATA_GROW);
1407
1408         customData_update_offsets(data);
1409         CustomData_update_typemap(data);
1410
1411         return 1;
1412 }
1413
1414 int CustomData_free_layer_active(CustomData *data, int type, int totelem)
1415 {
1416         int index = 0;
1417         index = CustomData_get_active_layer_index(data, type);
1418         if (index < 0) return 0;
1419         return CustomData_free_layer(data, type, totelem, index);
1420 }
1421
1422
1423 void CustomData_free_layers(CustomData *data, int type, int totelem)
1424 {
1425         while (CustomData_has_layer(data, type))
1426                 CustomData_free_layer_active(data, type, totelem);
1427 }
1428
1429 int CustomData_has_layer(const CustomData *data, int type)
1430 {
1431         return (CustomData_get_layer_index(data, type) != -1);
1432 }
1433
1434 int CustomData_number_of_layers(const CustomData *data, int type)
1435 {
1436         int i, number = 0;
1437
1438         for(i = 0; i < data->totlayer; i++)
1439                 if(data->layers[i].type == type)
1440                         number++;
1441         
1442         return number;
1443 }
1444
1445 void *CustomData_duplicate_referenced_layer(struct CustomData *data, const int type, const int totelem)
1446 {
1447         CustomDataLayer *layer;
1448         int layer_index;
1449
1450         /* get the layer index of the first layer of type */
1451         layer_index = CustomData_get_active_layer_index(data, type);
1452         if(layer_index < 0) return NULL;
1453
1454         layer = &data->layers[layer_index];
1455
1456         if (layer->flag & CD_FLAG_NOFREE) {
1457                 /* MEM_dupallocN won’t work in case of complex layers, like e.g.
1458                  * CD_MDEFORMVERT, which has pointers to allocated data...
1459                  * So in case a custom copy function is defined, use it!
1460                  */
1461                 const LayerTypeInfo *typeInfo = layerType_getInfo(layer->type);
1462
1463                 if(typeInfo->copy) {
1464                         char *dest_data = MEM_mallocN(typeInfo->size * totelem, "CD duplicate ref layer");
1465                         typeInfo->copy(layer->data, dest_data, totelem);
1466                         layer->data = dest_data;
1467                 }
1468                 else
1469                         layer->data = MEM_dupallocN(layer->data);
1470
1471                 layer->flag &= ~CD_FLAG_NOFREE;
1472         }
1473
1474         return layer->data;
1475 }
1476
1477 void *CustomData_duplicate_referenced_layer_named(struct CustomData *data,
1478                                                                                                   const int type, const char *name, const int totelem)
1479 {
1480         CustomDataLayer *layer;
1481         int layer_index;
1482
1483         /* get the layer index of the desired layer */
1484         layer_index = CustomData_get_named_layer_index(data, type, name);
1485         if(layer_index < 0) return NULL;
1486
1487         layer = &data->layers[layer_index];
1488
1489         if (layer->flag & CD_FLAG_NOFREE) {
1490                 /* MEM_dupallocN won’t work in case of complex layers, like e.g.
1491                  * CD_MDEFORMVERT, which has pointers to allocated data...
1492                  * So in case a custom copy function is defined, use it!
1493                  */
1494                 const LayerTypeInfo *typeInfo = layerType_getInfo(layer->type);
1495
1496                 if(typeInfo->copy) {
1497                         char *dest_data = MEM_mallocN(typeInfo->size * totelem, "CD duplicate ref layer");
1498                         typeInfo->copy(layer->data, dest_data, totelem);
1499                         layer->data = dest_data;
1500                 }
1501                 else
1502                         layer->data = MEM_dupallocN(layer->data);
1503
1504                 layer->flag &= ~CD_FLAG_NOFREE;
1505         }
1506
1507         return layer->data;
1508 }
1509
1510 int CustomData_is_referenced_layer(struct CustomData *data, int type)
1511 {
1512         CustomDataLayer *layer;
1513         int layer_index;
1514
1515         /* get the layer index of the first layer of type */
1516         layer_index = CustomData_get_active_layer_index(data, type);
1517         if(layer_index < 0) return 0;
1518
1519         layer = &data->layers[layer_index];
1520
1521         return (layer->flag & CD_FLAG_NOFREE) != 0;
1522 }
1523
1524 void CustomData_free_temporary(CustomData *data, int totelem)
1525 {
1526         CustomDataLayer *layer;
1527         int i, j;
1528
1529         for(i = 0, j = 0; i < data->totlayer; ++i) {
1530                 layer = &data->layers[i];
1531
1532                 if (i != j)
1533                         data->layers[j] = data->layers[i];
1534
1535                 if ((layer->flag & CD_FLAG_TEMPORARY) == CD_FLAG_TEMPORARY)
1536                         customData_free_layer__internal(layer, totelem);
1537                 else
1538                         j++;
1539         }
1540
1541         data->totlayer = j;
1542
1543         if(data->totlayer <= data->maxlayer-CUSTOMDATA_GROW)
1544                 customData_resize(data, -CUSTOMDATA_GROW);
1545
1546         customData_update_offsets(data);
1547 }
1548
1549 void CustomData_set_only_copy(const struct CustomData *data,
1550                               CustomDataMask mask)
1551 {
1552         int i;
1553
1554         for(i = 0; i < data->totlayer; ++i)
1555                 if(!(mask & CD_TYPE_AS_MASK(data->layers[i].type)))
1556                         data->layers[i].flag |= CD_FLAG_NOCOPY;
1557 }
1558
1559 void CustomData_copy_elements(int type, void *source, void *dest, int count)
1560 {
1561         const LayerTypeInfo *typeInfo = layerType_getInfo(type);
1562
1563         if (typeInfo->copy)
1564                 typeInfo->copy(source, dest, count);
1565         else
1566                 memcpy(dest, source, typeInfo->size*count);
1567 }
1568
1569 void CustomData_copy_data(const CustomData *source, CustomData *dest,
1570                                                   int source_index, int dest_index, int count)
1571 {
1572         const LayerTypeInfo *typeInfo;
1573         int src_i, dest_i;
1574         int src_offset;
1575         int dest_offset;
1576
1577         /* copies a layer at a time */
1578         dest_i = 0;
1579         for(src_i = 0; src_i < source->totlayer; ++src_i) {
1580
1581                 /* find the first dest layer with type >= the source type
1582                  * (this should work because layers are ordered by type)
1583                  */
1584                 while(dest_i < dest->totlayer
1585                           && dest->layers[dest_i].type < source->layers[src_i].type)
1586                         ++dest_i;
1587
1588                 /* if there are no more dest layers, we're done */
1589                 if(dest_i >= dest->totlayer) return;
1590
1591                 /* if we found a matching layer, copy the data */
1592                 if(dest->layers[dest_i].type == source->layers[src_i].type) {
1593                         char *src_data = source->layers[src_i].data;
1594                         char *dest_data = dest->layers[dest_i].data;
1595
1596                         typeInfo = layerType_getInfo(source->layers[src_i].type);
1597
1598                         src_offset = source_index * typeInfo->size;
1599                         dest_offset = dest_index * typeInfo->size;
1600                         
1601                         if (!src_data || !dest_data) {
1602                                 printf("%s: warning null data for %s type (%p --> %p), skipping\n",
1603                                        __func__, layerType_getName(source->layers[src_i].type),
1604                                        (void *)src_data, (void *)dest_data);
1605                                 continue;
1606                         }
1607                         
1608                         if(typeInfo->copy)
1609                                 typeInfo->copy(src_data + src_offset,
1610                                                                 dest_data + dest_offset,
1611                                                                 count);
1612                         else
1613                                 memcpy(dest_data + dest_offset,
1614                                            src_data + src_offset,
1615                                            count * typeInfo->size);
1616
1617                         /* if there are multiple source & dest layers of the same type,
1618                          * we don't want to copy all source layers to the same dest, so
1619                          * increment dest_i
1620                          */
1621                         ++dest_i;
1622                 }
1623         }
1624 }
1625
1626 void CustomData_free_elem(CustomData *data, int index, int count)
1627 {
1628         int i;
1629         const LayerTypeInfo *typeInfo;
1630
1631         for(i = 0; i < data->totlayer; ++i) {
1632                 if(!(data->layers[i].flag & CD_FLAG_NOFREE)) {
1633                         typeInfo = layerType_getInfo(data->layers[i].type);
1634
1635                         if(typeInfo->free) {
1636                                 int offset = typeInfo->size * index;
1637
1638                                 typeInfo->free((char *)data->layers[i].data + offset,
1639                                                            count, typeInfo->size);
1640                         }
1641                 }
1642         }
1643 }
1644
1645 #define SOURCE_BUF_SIZE 100
1646
1647 void CustomData_interp(const CustomData *source, CustomData *dest,
1648                                            int *src_indices, float *weights, float *sub_weights,
1649                                            int count, int dest_index)
1650 {
1651         int src_i, dest_i;
1652         int dest_offset;
1653         int j;
1654         void *source_buf[SOURCE_BUF_SIZE];
1655         void **sources = source_buf;
1656
1657         /* slow fallback in case we're interpolating a ridiculous number of
1658          * elements
1659          */
1660         if(count > SOURCE_BUF_SIZE)
1661                 sources = MEM_callocN(sizeof(*sources) * count,
1662                                                           "CustomData_interp sources");
1663
1664         /* interpolates a layer at a time */
1665         dest_i = 0;
1666         for(src_i = 0; src_i < source->totlayer; ++src_i) {
1667                 const LayerTypeInfo *typeInfo= layerType_getInfo(source->layers[src_i].type);
1668                 if(!typeInfo->interp) continue;
1669
1670                 /* find the first dest layer with type >= the source type
1671                  * (this should work because layers are ordered by type)
1672                  */
1673                 while(dest_i < dest->totlayer
1674                           && dest->layers[dest_i].type < source->layers[src_i].type)
1675                         ++dest_i;
1676
1677                 /* if there are no more dest layers, we're done */
1678                 if(dest_i >= dest->totlayer) return;
1679
1680                 /* if we found a matching layer, copy the data */
1681                 if(dest->layers[dest_i].type == source->layers[src_i].type) {
1682                         void *src_data = source->layers[src_i].data;
1683
1684                         for(j = 0; j < count; ++j)
1685                                 sources[j] = (char *)src_data
1686                                                          + typeInfo->size * src_indices[j];
1687
1688                         dest_offset = dest_index * typeInfo->size;
1689
1690                         typeInfo->interp(sources, weights, sub_weights, count,
1691                                                    (char *)dest->layers[dest_i].data + dest_offset);
1692
1693                         /* if there are multiple source & dest layers of the same type,
1694                          * we don't want to copy all source layers to the same dest, so
1695                          * increment dest_i
1696                          */
1697                         ++dest_i;
1698                 }
1699         }
1700
1701         if(count > SOURCE_BUF_SIZE) MEM_freeN(sources);
1702 }
1703
1704 void CustomData_swap(struct CustomData *data, int index, const int *corner_indices)
1705 {
1706         const LayerTypeInfo *typeInfo;
1707         int i;
1708
1709         for(i = 0; i < data->totlayer; ++i) {
1710                 typeInfo = layerType_getInfo(data->layers[i].type);
1711
1712                 if(typeInfo->swap) {
1713                         int offset = typeInfo->size * index;
1714
1715                         typeInfo->swap((char *)data->layers[i].data + offset, corner_indices);
1716                 }
1717         }
1718 }
1719
1720 void *CustomData_get(const CustomData *data, int index, int type)
1721 {
1722         int offset;
1723         int layer_index;
1724         
1725         /* get the layer index of the active layer of type */
1726         layer_index = CustomData_get_active_layer_index(data, type);
1727         if(layer_index < 0) return NULL;
1728
1729         /* get the offset of the desired element */
1730         offset = layerType_getInfo(type)->size * index;
1731
1732         return (char *)data->layers[layer_index].data + offset;
1733 }
1734
1735 void *CustomData_get_n(const CustomData *data, int type, int index, int n)
1736 {
1737         int layer_index;
1738         int offset;
1739
1740         /* get the layer index of the first layer of type */
1741         layer_index = data->typemap[type];
1742         if(layer_index < 0) return NULL;
1743
1744         offset = layerType_getInfo(type)->size * index;
1745         return (char *)data->layers[layer_index+n].data + offset;
1746 }
1747
1748 void *CustomData_get_layer(const CustomData *data, int type)
1749 {
1750         /* get the layer index of the active layer of type */
1751         int layer_index = CustomData_get_active_layer_index(data, type);
1752         if(layer_index < 0) return NULL;
1753
1754         return data->layers[layer_index].data;
1755 }
1756
1757 void *CustomData_get_layer_n(const CustomData *data, int type, int n)
1758 {
1759         /* get the layer index of the active layer of type */
1760         int layer_index = CustomData_get_layer_index_n(data, type, n);
1761         if(layer_index < 0) return NULL;
1762
1763         return data->layers[layer_index].data;
1764 }
1765
1766 void *CustomData_get_layer_named(const struct CustomData *data, int type,
1767                                                                  const char *name)
1768 {
1769         int layer_index = CustomData_get_named_layer_index(data, type, name);
1770         if(layer_index < 0) return NULL;
1771
1772         return data->layers[layer_index].data;
1773 }
1774
1775
1776 int CustomData_set_layer_name(const CustomData *data, int type, int n, const char *name)
1777 {
1778         /* get the layer index of the first layer of type */
1779         int layer_index = CustomData_get_layer_index_n(data, type, n);
1780
1781         if(layer_index < 0) return 0;
1782         if (!name) return 0;
1783         
1784         strcpy(data->layers[layer_index].name, name);
1785         
1786         return 1;
1787 }
1788
1789 void *CustomData_set_layer(const CustomData *data, int type, void *ptr)
1790 {
1791         /* get the layer index of the first layer of type */
1792         int layer_index = CustomData_get_active_layer_index(data, type);
1793
1794         if(layer_index < 0) return NULL;
1795
1796         data->layers[layer_index].data = ptr;
1797
1798         return ptr;
1799 }
1800
1801 void *CustomData_set_layer_n(const struct CustomData *data, int type, int n, void *ptr)
1802 {
1803         /* get the layer index of the first layer of type */
1804         int layer_index = CustomData_get_layer_index_n(data, type, n);
1805         if(layer_index < 0) return NULL;
1806
1807         data->layers[layer_index].data = ptr;
1808
1809         return ptr;
1810 }
1811
1812 void CustomData_set(const CustomData *data, int index, int type, void *source)
1813 {
1814         void *dest = CustomData_get(data, index, type);
1815         const LayerTypeInfo *typeInfo = layerType_getInfo(type);
1816
1817         if(!dest) return;
1818
1819         if(typeInfo->copy)
1820                 typeInfo->copy(source, dest, 1);
1821         else
1822                 memcpy(dest, source, typeInfo->size);
1823 }
1824
1825 /* EditMesh functions */
1826
1827 void CustomData_em_free_block(CustomData *data, void **block)
1828 {
1829         const LayerTypeInfo *typeInfo;
1830         int i;
1831
1832         if(!*block) return;
1833
1834         for(i = 0; i < data->totlayer; ++i) {
1835                 if(!(data->layers[i].flag & CD_FLAG_NOFREE)) {
1836                         typeInfo = layerType_getInfo(data->layers[i].type);
1837
1838                         if(typeInfo->free) {
1839                                 int offset = data->layers[i].offset;
1840                                 typeInfo->free((char*)*block + offset, 1, typeInfo->size);
1841                         }
1842                 }
1843         }
1844
1845         MEM_freeN(*block);
1846         *block = NULL;
1847 }
1848
1849 static void CustomData_em_alloc_block(CustomData *data, void **block)
1850 {
1851         /* TODO: optimize free/alloc */
1852
1853         if (*block)
1854                 CustomData_em_free_block(data, block);
1855
1856         if (data->totsize > 0)
1857                 *block = MEM_callocN(data->totsize, "CustomData EM block");
1858         else
1859                 *block = NULL;
1860 }
1861
1862 void CustomData_em_copy_data(const CustomData *source, CustomData *dest,
1863                                                         void *src_block, void **dest_block)
1864 {
1865         const LayerTypeInfo *typeInfo;
1866         int dest_i, src_i;
1867
1868         if (!*dest_block)
1869                 CustomData_em_alloc_block(dest, dest_block);
1870         
1871         /* copies a layer at a time */
1872         dest_i = 0;
1873         for(src_i = 0; src_i < source->totlayer; ++src_i) {
1874
1875                 /* find the first dest layer with type >= the source type
1876                  * (this should work because layers are ordered by type)
1877                  */
1878                 while(dest_i < dest->totlayer
1879                           && dest->layers[dest_i].type < source->layers[src_i].type)
1880                         ++dest_i;
1881
1882                 /* if there are no more dest layers, we're done */
1883                 if(dest_i >= dest->totlayer) return;
1884
1885                 /* if we found a matching layer, copy the data */
1886                 if(dest->layers[dest_i].type == source->layers[src_i].type &&
1887                         strcmp(dest->layers[dest_i].name, source->layers[src_i].name) == 0) {
1888                         char *src_data = (char*)src_block + source->layers[src_i].offset;
1889                         char *dest_data = (char*)*dest_block + dest->layers[dest_i].offset;
1890
1891                         typeInfo = layerType_getInfo(source->layers[src_i].type);
1892
1893                         if(typeInfo->copy)
1894                                 typeInfo->copy(src_data, dest_data, 1);
1895                         else
1896                                 memcpy(dest_data, src_data, typeInfo->size);
1897
1898                         /* if there are multiple source & dest layers of the same type,
1899                          * we don't want to copy all source layers to the same dest, so
1900                          * increment dest_i
1901                          */
1902                         ++dest_i;
1903                 }
1904         }
1905 }
1906
1907 void CustomData_em_validate_data(CustomData *data, void *block, int sub_elements)
1908 {
1909         int i;
1910         for(i = 0; i < data->totlayer; i++) {
1911                 const LayerTypeInfo *typeInfo = layerType_getInfo(data->layers[i].type);
1912                 char *leayer_data = (char*)block + data->layers[i].offset;
1913
1914                 if(typeInfo->validate)
1915                         typeInfo->validate(leayer_data, sub_elements);
1916         }
1917 }
1918
1919 void *CustomData_em_get(const CustomData *data, void *block, int type)
1920 {
1921         int layer_index;
1922         
1923         /* get the layer index of the first layer of type */
1924         layer_index = CustomData_get_active_layer_index(data, type);
1925         if(layer_index < 0) return NULL;
1926
1927         return (char *)block + data->layers[layer_index].offset;
1928 }
1929
1930 void *CustomData_em_get_n(const CustomData *data, void *block, int type, int n)
1931 {
1932         int layer_index;
1933         
1934         /* get the layer index of the first layer of type */
1935         layer_index = CustomData_get_layer_index_n(data, type, n);
1936         if(layer_index < 0) return NULL;
1937
1938         return (char *)block + data->layers[layer_index].offset;
1939 }
1940
1941 void CustomData_em_set(CustomData *data, void *block, int type, void *source)
1942 {
1943         void *dest = CustomData_em_get(data, block, type);
1944         const LayerTypeInfo *typeInfo = layerType_getInfo(type);
1945
1946         if(!dest) return;
1947
1948         if(typeInfo->copy)
1949                 typeInfo->copy(source, dest, 1);
1950         else
1951                 memcpy(dest, source, typeInfo->size);
1952 }
1953
1954 void CustomData_em_set_n(CustomData *data, void *block, int type, int n, void *source)
1955 {
1956         void *dest = CustomData_em_get_n(data, block, type, n);
1957         const LayerTypeInfo *typeInfo = layerType_getInfo(type);
1958
1959         if(!dest) return;
1960
1961         if(typeInfo->copy)
1962                 typeInfo->copy(source, dest, 1);
1963         else
1964                 memcpy(dest, source, typeInfo->size);
1965 }
1966
1967 void CustomData_em_interp(CustomData *data, void **src_blocks, float *weights,
1968                                                   float *sub_weights, int count, void *dest_block)
1969 {
1970         int i, j;
1971         void *source_buf[SOURCE_BUF_SIZE];
1972         void **sources = source_buf;
1973
1974         /* slow fallback in case we're interpolating a ridiculous number of
1975          * elements
1976          */
1977         if(count > SOURCE_BUF_SIZE)
1978                 sources = MEM_callocN(sizeof(*sources) * count,
1979                                                           "CustomData_interp sources");
1980
1981         /* interpolates a layer at a time */
1982         for(i = 0; i < data->totlayer; ++i) {
1983                 CustomDataLayer *layer = &data->layers[i];
1984                 const LayerTypeInfo *typeInfo = layerType_getInfo(layer->type);
1985
1986                 if(typeInfo->interp) {
1987                         for(j = 0; j < count; ++j)
1988                                 sources[j] = (char *)src_blocks[j] + layer->offset;
1989
1990                         typeInfo->interp(sources, weights, sub_weights, count,
1991                                                           (char *)dest_block + layer->offset);
1992                 }
1993         }
1994
1995         if(count > SOURCE_BUF_SIZE) MEM_freeN(sources);
1996 }
1997
1998 void CustomData_em_set_default(CustomData *data, void **block)
1999 {
2000         const LayerTypeInfo *typeInfo;
2001         int i;
2002
2003         if (!*block)
2004                 CustomData_em_alloc_block(data, block);
2005
2006         for(i = 0; i < data->totlayer; ++i) {
2007                 int offset = data->layers[i].offset;
2008
2009                 typeInfo = layerType_getInfo(data->layers[i].type);
2010
2011                 if(typeInfo->set_default)
2012                         typeInfo->set_default((char*)*block + offset, 1);
2013         }
2014 }
2015
2016 void CustomData_to_em_block(const CustomData *source, CustomData *dest,
2017                                                         int src_index, void **dest_block)
2018 {
2019         const LayerTypeInfo *typeInfo;
2020         int dest_i, src_i, src_offset;
2021
2022         if (!*dest_block)
2023                 CustomData_em_alloc_block(dest, dest_block);
2024         
2025         /* copies a layer at a time */
2026         dest_i = 0;
2027         for(src_i = 0; src_i < source->totlayer; ++src_i) {
2028
2029                 /* find the first dest layer with type >= the source type
2030                  * (this should work because layers are ordered by type)
2031                  */
2032                 while(dest_i < dest->totlayer
2033                           && dest->layers[dest_i].type < source->layers[src_i].type)
2034                         ++dest_i;
2035
2036                 /* if there are no more dest layers, we're done */
2037                 if(dest_i >= dest->totlayer) return;
2038
2039                 /* if we found a matching layer, copy the data */
2040                 if(dest->layers[dest_i].type == source->layers[src_i].type) {
2041                         int offset = dest->layers[dest_i].offset;
2042                         char *src_data = source->layers[src_i].data;
2043                         char *dest_data = (char*)*dest_block + offset;
2044
2045                         typeInfo = layerType_getInfo(dest->layers[dest_i].type);
2046                         src_offset = src_index * typeInfo->size;
2047
2048                         if(typeInfo->copy)
2049                                 typeInfo->copy(src_data + src_offset, dest_data, 1);
2050                         else
2051                                 memcpy(dest_data, src_data + src_offset, typeInfo->size);
2052
2053                         /* if there are multiple source & dest layers of the same type,
2054                          * we don't want to copy all source layers to the same dest, so
2055                          * increment dest_i
2056                          */
2057                         ++dest_i;
2058                 }
2059         }
2060 }
2061
2062 void CustomData_from_em_block(const CustomData *source, CustomData *dest,
2063                                                           void *src_block, int dest_index)
2064 {
2065         const LayerTypeInfo *typeInfo;
2066         int dest_i, src_i, dest_offset;
2067
2068         /* copies a layer at a time */
2069         dest_i = 0;
2070         for(src_i = 0; src_i < source->totlayer; ++src_i) {
2071
2072                 /* find the first dest layer with type >= the source type
2073                  * (this should work because layers are ordered by type)
2074                  */
2075                 while(dest_i < dest->totlayer
2076                           && dest->layers[dest_i].type < source->layers[src_i].type)
2077                         ++dest_i;
2078
2079                 /* if there are no more dest layers, we're done */
2080                 if(dest_i >= dest->totlayer) return;
2081
2082                 /* if we found a matching layer, copy the data */
2083                 if(dest->layers[dest_i].type == source->layers[src_i].type) {
2084                         int offset = source->layers[src_i].offset;
2085                         char *src_data = (char*)src_block + offset;
2086                         char *dest_data = dest->layers[dest_i].data;
2087
2088                         typeInfo = layerType_getInfo(dest->layers[dest_i].type);
2089                         dest_offset = dest_index * typeInfo->size;
2090
2091                         if(typeInfo->copy)
2092                                 typeInfo->copy(src_data, dest_data + dest_offset, 1);
2093                         else
2094                                 memcpy(dest_data + dest_offset, src_data, typeInfo->size);
2095
2096                         /* if there are multiple source & dest layers of the same type,
2097                          * we don't want to copy all source layers to the same dest, so
2098                          * increment dest_i
2099                          */
2100                         ++dest_i;
2101                 }
2102         }
2103
2104 }
2105
2106 /*Bmesh functions*/
2107 /*needed to convert to/from different face reps*/
2108 void CustomData_to_bmeshpoly(CustomData *fdata, CustomData *pdata, CustomData *ldata)
2109 {
2110         int i;
2111         for(i=0; i < fdata->totlayer; i++){
2112                 if(fdata->layers[i].type == CD_MTFACE){
2113                         CustomData_add_layer(pdata, CD_MTEXPOLY, CD_CALLOC, &(fdata->layers[i].name), 0);
2114                         CustomData_add_layer(ldata, CD_MLOOPUV, CD_CALLOC, &(fdata->layers[i].name), 0);
2115                 }
2116                 else if(fdata->layers[i].type == CD_MCOL)
2117                         CustomData_add_layer(ldata, CD_MLOOPCOL, CD_CALLOC, &(fdata->layers[i].name), 0);
2118         }               
2119 }
2120 void CustomData_from_bmeshpoly(CustomData *fdata, CustomData *pdata, CustomData *ldata, int total)
2121 {
2122         int i;
2123         for(i=0; i < pdata->totlayer; i++){
2124                 if(pdata->layers[i].type == CD_MTEXPOLY)
2125                         CustomData_add_layer(fdata, CD_MTFACE, CD_CALLOC, &(pdata->layers[i].name), total);
2126         }
2127         for(i=0; i < ldata->totlayer; i++){
2128                 if(ldata->layers[i].type == CD_MLOOPCOL)
2129                         CustomData_add_layer(fdata, CD_MCOL, CD_CALLOC, &(ldata->layers[i].name), total);
2130         }
2131 }
2132
2133
2134 void CustomData_bmesh_init_pool(CustomData *data, int allocsize)
2135 {
2136         if(data->totlayer)data->pool = BLI_mempool_create(data->totsize, allocsize, allocsize, FALSE, FALSE);
2137 }
2138
2139 void CustomData_bmesh_free_block(CustomData *data, void **block)
2140 {
2141         const LayerTypeInfo *typeInfo;
2142         int i;
2143
2144         if(!*block) return;
2145         for(i = 0; i < data->totlayer; ++i) {
2146                 if(!(data->layers[i].flag & CD_FLAG_NOFREE)) {
2147                         typeInfo = layerType_getInfo(data->layers[i].type);
2148
2149                         if(typeInfo->free) {
2150                                 int offset = data->layers[i].offset;
2151                                 typeInfo->free((char*)*block + offset, 1, typeInfo->size);
2152                         }
2153                 }
2154         }
2155
2156         BLI_mempool_free(data->pool, *block);
2157         *block = NULL;
2158 }
2159
2160 static void CustomData_bmesh_alloc_block(CustomData *data, void **block)
2161 {
2162
2163         if (*block)
2164                 CustomData_bmesh_free_block(data, block);
2165
2166         if (data->totsize > 0)
2167                 *block = BLI_mempool_calloc(data->pool);
2168         else
2169                 *block = NULL;
2170 }
2171
2172 void CustomData_bmesh_copy_data(const CustomData *source, CustomData *dest,
2173                                                         void *src_block, void **dest_block)
2174 {
2175         const LayerTypeInfo *typeInfo;
2176         int dest_i, src_i;
2177
2178         if (!*dest_block)
2179                 CustomData_bmesh_alloc_block(dest, dest_block);
2180         
2181         /* copies a layer at a time */
2182         dest_i = 0;
2183         for(src_i = 0; src_i < source->totlayer; ++src_i) {
2184
2185                 /* find the first dest layer with type >= the source type
2186                  * (this should work because layers are ordered by type)
2187                  */
2188                 while(dest_i < dest->totlayer
2189                           && dest->layers[dest_i].type < source->layers[src_i].type)
2190                         ++dest_i;
2191
2192                 /* if there are no more dest layers, we're done */
2193                 if(dest_i >= dest->totlayer) return;
2194
2195                 /* if we found a matching layer, copy the data */
2196                 if(dest->layers[dest_i].type == source->layers[src_i].type &&
2197                         strcmp(dest->layers[dest_i].name, source->layers[src_i].name) == 0) {
2198                         char *src_data = (char*)src_block + source->layers[src_i].offset;
2199                         char *dest_data = (char*)*dest_block + dest->layers[dest_i].offset;
2200
2201                         typeInfo = layerType_getInfo(source->layers[src_i].type);
2202
2203                         if(typeInfo->copy)
2204                                 typeInfo->copy(src_data, dest_data, 1);
2205                         else
2206                                 memcpy(dest_data, src_data, typeInfo->size);
2207
2208                         /* if there are multiple source & dest layers of the same type,
2209                          * we don't want to copy all source layers to the same dest, so
2210                          * increment dest_i
2211                          */
2212                         ++dest_i;
2213                 }
2214         }
2215 }
2216
2217 /*Bmesh Custom Data Functions. Should replace editmesh ones with these as well, due to more effecient memory alloc*/
2218 void *CustomData_bmesh_get(const CustomData *data, void *block, int type)
2219 {
2220         int layer_index;
2221         
2222         /* get the layer index of the first layer of type */
2223         layer_index = CustomData_get_active_layer_index(data, type);
2224         if(layer_index < 0) return NULL;
2225
2226         return (char *)block + data->layers[layer_index].offset;
2227 }
2228
2229 void *CustomData_bmesh_get_n(const CustomData *data, void *block, int type, int n)
2230 {
2231         int layer_index;
2232         
2233         /* get the layer index of the first layer of type */
2234         layer_index = CustomData_get_layer_index(data, type);
2235         if(layer_index < 0) return NULL;
2236
2237         return (char *)block + data->layers[layer_index+n].offset;
2238 }
2239
2240 /*gets from the layer at physical index n, note: doesn't check type.*/
2241 void *CustomData_bmesh_get_layer_n(const CustomData *data, void *block, int n)
2242 {
2243         if(n < 0 || n >= data->totlayer) return NULL;
2244
2245         return (char *)block + data->layers[n].offset;
2246 }
2247
2248
2249 void CustomData_bmesh_set(const CustomData *data, void *block, int type, void *source)
2250 {
2251         void *dest = CustomData_bmesh_get(data, block, type);
2252         const LayerTypeInfo *typeInfo = layerType_getInfo(type);
2253
2254         if(!dest) return;
2255
2256         if(typeInfo->copy)
2257                 typeInfo->copy(source, dest, 1);
2258         else
2259                 memcpy(dest, source, typeInfo->size);
2260 }
2261
2262 void CustomData_bmesh_set_n(CustomData *data, void *block, int type, int n, void *source)
2263 {
2264         void *dest = CustomData_bmesh_get_n(data, block, type, n);
2265         const LayerTypeInfo *typeInfo = layerType_getInfo(type);
2266
2267         if(!dest) return;
2268
2269         if(typeInfo->copy)
2270                 typeInfo->copy(source, dest, 1);
2271         else
2272                 memcpy(dest, source, typeInfo->size);
2273 }
2274
2275 void CustomData_bmesh_set_layer_n(CustomData *data, void *block, int n, void *source)
2276 {
2277         void *dest = CustomData_bmesh_get_layer_n(data, block, n);
2278         const LayerTypeInfo *typeInfo = layerType_getInfo(data->layers[n].type);
2279
2280         if(!dest) return;
2281
2282         if(typeInfo->copy)
2283                 typeInfo->copy(source, dest, 1);
2284         else
2285                 memcpy(dest, source, typeInfo->size);
2286 }
2287
2288 void CustomData_bmesh_interp(CustomData *data, void **src_blocks, float *weights,
2289                                                   float *sub_weights, int count, void *dest_block)
2290 {
2291         int i, j;
2292         void *source_buf[SOURCE_BUF_SIZE];
2293         void **sources = source_buf;
2294
2295         /* slow fallback in case we're interpolating a ridiculous number of
2296          * elements
2297          */
2298         if(count > SOURCE_BUF_SIZE)
2299                 sources = MEM_callocN(sizeof(*sources) * count,
2300                                                           "CustomData_interp sources");
2301
2302         /* interpolates a layer at a time */
2303         for(i = 0; i < data->totlayer; ++i) {
2304                 CustomDataLayer *layer = &data->layers[i];
2305                 const LayerTypeInfo *typeInfo = layerType_getInfo(layer->type);
2306                 if(typeInfo->interp) {
2307                         for(j = 0; j < count; ++j)
2308                                 sources[j] = (char *)src_blocks[j] + layer->offset;
2309
2310                         typeInfo->interp(sources, weights, sub_weights, count,
2311                                                           (char *)dest_block + layer->offset);
2312                 }
2313         }
2314
2315         if(count > SOURCE_BUF_SIZE) MEM_freeN(sources);
2316 }
2317
2318 void CustomData_bmesh_set_default(CustomData *data, void **block)
2319 {
2320         const LayerTypeInfo *typeInfo;
2321         int i;
2322
2323         if (!*block)
2324                 CustomData_bmesh_alloc_block(data, block);
2325
2326         for(i = 0; i < data->totlayer; ++i) {
2327                 int offset = data->layers[i].offset;
2328
2329                 typeInfo = layerType_getInfo(data->layers[i].type);
2330
2331                 if(typeInfo->set_default)
2332                         typeInfo->set_default((char*)*block + offset, 1);
2333                 else memset((char*)*block + offset, 0, typeInfo->size);
2334         }
2335 }
2336
2337 void CustomData_to_bmesh_block(const CustomData *source, CustomData *dest,
2338                                                         int src_index, void **dest_block)
2339 {
2340         const LayerTypeInfo *typeInfo;
2341         int dest_i, src_i, src_offset;
2342
2343         if (!*dest_block)
2344                 CustomData_bmesh_alloc_block(dest, dest_block);
2345         
2346         /* copies a layer at a time */
2347         dest_i = 0;
2348         for(src_i = 0; src_i < source->totlayer; ++src_i) {
2349
2350                 /* find the first dest layer with type >= the source type
2351                  * (this should work because layers are ordered by type)
2352                  */
2353                 while(dest_i < dest->totlayer
2354                           && dest->layers[dest_i].type < source->layers[src_i].type)
2355                         ++dest_i;
2356
2357                 /* if there are no more dest layers, we're done */
2358                 if(dest_i >= dest->totlayer) return;
2359
2360                 /* if we found a matching layer, copy the data */
2361                 if(dest->layers[dest_i].type == source->layers[src_i].type) {
2362                         int offset = dest->layers[dest_i].offset;
2363                         char *src_data = source->layers[src_i].data;
2364                         char *dest_data = (char*)*dest_block + offset;
2365
2366                         typeInfo = layerType_getInfo(dest->layers[dest_i].type);
2367                         src_offset = src_index * typeInfo->size;
2368
2369                         if(typeInfo->copy)
2370                                 typeInfo->copy(src_data + src_offset, dest_data, 1);
2371                         else
2372                                 memcpy(dest_data, src_data + src_offset, typeInfo->size);
2373
2374                         /* if there are multiple source & dest layers of the same type,
2375                          * we don't want to copy all source layers to the same dest, so
2376                          * increment dest_i
2377                          */
2378                         ++dest_i;
2379                 }
2380         }
2381 }
2382
2383 void CustomData_from_bmesh_block(const CustomData *source, CustomData *dest,
2384                                                           void *src_block, int dest_index)
2385 {
2386         const LayerTypeInfo *typeInfo;
2387         int dest_i, src_i, dest_offset;
2388
2389         /* copies a layer at a time */
2390         dest_i = 0;
2391         for(src_i = 0; src_i < source->totlayer; ++src_i) {
2392
2393                 /* find the first dest layer with type >= the source type
2394                  * (this should work because layers are ordered by type)
2395                  */
2396                 while(dest_i < dest->totlayer
2397                           && dest->layers[dest_i].type < source->layers[src_i].type)
2398                         ++dest_i;
2399
2400                 /* if there are no more dest layers, we're done */
2401                 if(dest_i >= dest->totlayer) return;
2402
2403                 /* if we found a matching layer, copy the data */
2404                 if(dest->layers[dest_i].type == source->layers[src_i].type) {
2405                         int offset = source->layers[src_i].offset;
2406                         char *src_data = (char*)src_block + offset;
2407                         char *dest_data = dest->layers[dest_i].data;
2408
2409                         typeInfo = layerType_getInfo(dest->layers[dest_i].type);
2410                         dest_offset = dest_index * typeInfo->size;
2411
2412                         if(typeInfo->copy)
2413                                 typeInfo->copy(src_data, dest_data + dest_offset, 1);
2414                         else
2415                                 memcpy(dest_data + dest_offset, src_data, typeInfo->size);
2416
2417                         /* if there are multiple source & dest layers of the same type,
2418                          * we don't want to copy all source layers to the same dest, so
2419                          * increment dest_i
2420                          */
2421                         ++dest_i;
2422                 }
2423         }
2424
2425 }
2426
2427 void CustomData_file_write_info(int type, const char **structname, int *structnum)
2428 {
2429         const LayerTypeInfo *typeInfo = layerType_getInfo(type);
2430
2431         *structname = typeInfo->structname;
2432         *structnum = typeInfo->structnum;
2433 }
2434
2435 int CustomData_sizeof(int type)
2436 {
2437         const LayerTypeInfo *typeInfo = layerType_getInfo(type);
2438
2439         return typeInfo->size;
2440 }
2441
2442 const char *CustomData_layertype_name(int type)
2443 {
2444         return layerType_getName(type);
2445 }
2446
2447 static int  CustomData_is_property_layer(int type)
2448 {
2449         if((type == CD_PROP_FLT) || (type == CD_PROP_INT) || (type == CD_PROP_STR))
2450                 return 1;
2451         return 0;
2452 }
2453
2454 static int cd_layer_find_dupe(CustomData *data, const char *name, int type, int index)
2455 {
2456         int i;
2457         /* see if there is a duplicate */
2458         for(i=0; i<data->totlayer; i++) {
2459                 if(i != index) {
2460                         CustomDataLayer *layer= &data->layers[i];
2461                         
2462                         if(CustomData_is_property_layer(type)) {
2463                                 if(CustomData_is_property_layer(layer->type) && strcmp(layer->name, name)==0) {
2464                                         return 1;
2465                                 }
2466                         }
2467                         else{
2468                                 if(i!=index && layer->type==type && strcmp(layer->name, name)==0) {
2469                                         return 1;
2470                                 }
2471                         }
2472                 }
2473         }
2474         
2475         return 0;
2476 }
2477
2478 static int customdata_unique_check(void *arg, const char *name)
2479 {
2480         struct {CustomData *data; int type; int index;} *data_arg= arg;
2481         return cd_layer_find_dupe(data_arg->data, name, data_arg->type, data_arg->index);
2482 }
2483
2484 void CustomData_set_layer_unique_name(CustomData *data, int index)
2485 {       
2486         CustomDataLayer *nlayer= &data->layers[index];
2487         const LayerTypeInfo *typeInfo= layerType_getInfo(nlayer->type);
2488
2489         struct {CustomData *data; int type; int index;} data_arg;
2490         data_arg.data= data;
2491         data_arg.type= nlayer->type;
2492         data_arg.index= index;
2493
2494         if (!typeInfo->defaultname)
2495                 return;
2496         
2497         BLI_uniquename_cb(customdata_unique_check, &data_arg, typeInfo->defaultname, '.', nlayer->name, sizeof(nlayer->name));
2498 }
2499
2500 void CustomData_validate_layer_name(const CustomData *data, int type, char *name, char *outname)
2501 {
2502         int index = -1;
2503
2504         /* if a layer name was given, try to find that layer */
2505         if(name[0])
2506                 index = CustomData_get_named_layer_index(data, type, name);
2507
2508         if(index < 0) {
2509                 /* either no layer was specified, or the layer we want has been
2510                 * deleted, so assign the active layer to name
2511                 */
2512                 index = CustomData_get_active_layer_index(data, type);
2513                 strcpy(outname, data->layers[index].name);
2514         }
2515         else
2516                 strcpy(outname, name);
2517 }
2518
2519 int CustomData_verify_versions(struct CustomData *data, int index)
2520 {
2521         const LayerTypeInfo *typeInfo;
2522         CustomDataLayer *layer = &data->layers[index];
2523         int i, keeplayer = 1;
2524
2525         if (layer->type >= CD_NUMTYPES) {
2526                 keeplayer = 0; /* unknown layer type from future version */
2527         }
2528         else {
2529                 typeInfo = layerType_getInfo(layer->type);
2530
2531                 if (!typeInfo->defaultname && (index > 0) &&
2532                         data->layers[index-1].type == layer->type)
2533                         keeplayer = 0; /* multiple layers of which we only support one */
2534         }
2535
2536         if (!keeplayer) {
2537                 for (i=index+1; i < data->totlayer; ++i)
2538                         data->layers[i-1] = data->layers[i];
2539                 data->totlayer--;
2540         }
2541
2542         return keeplayer;
2543 }
2544
2545 /****************************** External Files *******************************/
2546
2547 static void customdata_external_filename(char filename[FILE_MAX], ID *id, CustomDataExternal *external)
2548 {
2549         BLI_strncpy(filename, external->filename, FILE_MAX);
2550         BLI_path_abs(filename, ID_BLEND_PATH(G.main, id));
2551 }
2552
2553 void CustomData_external_reload(CustomData *data, ID *UNUSED(id), CustomDataMask mask, int totelem)
2554 {
2555         CustomDataLayer *layer;
2556         const LayerTypeInfo *typeInfo;
2557         int i;
2558
2559         for(i=0; i<data->totlayer; i++) {
2560                 layer = &data->layers[i];
2561                 typeInfo = layerType_getInfo(layer->type);
2562
2563                 if(!(mask & CD_TYPE_AS_MASK(layer->type)));
2564                 else if((layer->flag & CD_FLAG_EXTERNAL) && (layer->flag & CD_FLAG_IN_MEMORY)) {
2565                         if(typeInfo->free)
2566                                 typeInfo->free(layer->data, totelem, typeInfo->size);
2567                         layer->flag &= ~CD_FLAG_IN_MEMORY;
2568                 }
2569         }
2570 }
2571
2572 void CustomData_external_read(CustomData *data, ID *id, CustomDataMask mask, int totelem)
2573 {
2574         CustomDataExternal *external= data->external;
2575         CustomDataLayer *layer;
2576         CDataFile *cdf;
2577         CDataFileLayer *blay;
2578         char filename[FILE_MAX];
2579         const LayerTypeInfo *typeInfo;
2580         int i, update = 0;
2581
2582         if(!external)
2583                 return;
2584         
2585         for(i=0; i<data->totlayer; i++) {
2586                 layer = &data->layers[i];
2587                 typeInfo = layerType_getInfo(layer->type);
2588
2589                 if(!(mask & CD_TYPE_AS_MASK(layer->type)));
2590                 else if(layer->flag & CD_FLAG_IN_MEMORY);
2591                 else if((layer->flag & CD_FLAG_EXTERNAL) && typeInfo->read)
2592                         update= 1;
2593         }
2594
2595         if(!update)
2596                 return;
2597
2598         customdata_external_filename(filename, id, external);
2599
2600         cdf= cdf_create(CDF_TYPE_MESH);
2601         if(!cdf_read_open(cdf, filename)) {
2602                 fprintf(stderr, "Failed to read %s layer from %s.\n", layerType_getName(layer->type), filename);
2603                 return;
2604         }
2605
2606         for(i=0; i<data->totlayer; i++) {
2607                 layer = &data->layers[i];
2608                 typeInfo = layerType_getInfo(layer->type);
2609
2610                 if(!(mask & CD_TYPE_AS_MASK(layer->type)));
2611                 else if(layer->flag & CD_FLAG_IN_MEMORY);
2612                 else if((layer->flag & CD_FLAG_EXTERNAL) && typeInfo->read) {
2613                         blay= cdf_layer_find(cdf, layer->type, layer->name);
2614
2615                         if(blay) {
2616                                 if(cdf_read_layer(cdf, blay)) {
2617                                         if(typeInfo->read(cdf, layer->data, totelem));
2618                                         else break;
2619                                         layer->flag |= CD_FLAG_IN_MEMORY;
2620                                 }
2621                                 else
2622                                         break;
2623                         }
2624                 }
2625         }
2626
2627         cdf_read_close(cdf);
2628         cdf_free(cdf);
2629 }
2630
2631 void CustomData_external_write(CustomData *data, ID *id, CustomDataMask mask, int totelem, int free)
2632 {
2633         CustomDataExternal *external= data->external;
2634         CustomDataLayer *layer;
2635         CDataFile *cdf;
2636         CDataFileLayer *blay;
2637         const LayerTypeInfo *typeInfo;
2638         int i, update = 0;
2639         char filename[FILE_MAX];
2640
2641         if(!external)
2642                 return;
2643
2644         /* test if there is anything to write */
2645         for(i=0; i<data->totlayer; i++) {
2646                 layer = &data->layers[i];
2647                 typeInfo = layerType_getInfo(layer->type);
2648
2649                 if(!(mask & CD_TYPE_AS_MASK(layer->type)));
2650                 else if((layer->flag & CD_FLAG_EXTERNAL) && typeInfo->write)
2651                         update= 1;
2652         }
2653
2654         if(!update)
2655                 return;
2656
2657         /* make sure data is read before we try to write */
2658         CustomData_external_read(data, id, mask, totelem);
2659         customdata_external_filename(filename, id, external);
2660
2661         cdf= cdf_create(CDF_TYPE_MESH);
2662
2663         for(i=0; i<data->totlayer; i++) {
2664                 layer = &data->layers[i];
2665                 typeInfo = layerType_getInfo(layer->type);
2666
2667                 if((layer->flag & CD_FLAG_EXTERNAL) && typeInfo->filesize) {
2668                         if(layer->flag & CD_FLAG_IN_MEMORY) {
2669                                 cdf_layer_add(cdf, layer->type, layer->name,
2670                                         typeInfo->filesize(cdf, layer->data, totelem));
2671                         }
2672                         else {
2673                                 cdf_free(cdf);
2674                                 return; /* read failed for a layer! */
2675                         }
2676                 }
2677         }
2678
2679         if(!cdf_write_open(cdf, filename)) {
2680                 fprintf(stderr, "Failed to open %s for writing.\n", filename);
2681                 return;
2682         }
2683
2684         for(i=0; i<data->totlayer; i++) {
2685                 layer = &data->layers[i];
2686                 typeInfo = layerType_getInfo(layer->type);
2687
2688                 if((layer->flag & CD_FLAG_EXTERNAL) && typeInfo->write) {
2689                         blay= cdf_layer_find(cdf, layer->type, layer->name);
2690
2691                         if(cdf_write_layer(cdf, blay)) {
2692                                 if(typeInfo->write(cdf, layer->data, totelem));
2693                                 else break;
2694                         }
2695                         else
2696                                 break;
2697                 }
2698         }
2699
2700         if(i != data->totlayer) {
2701                 fprintf(stderr, "Failed to write data to %s.\n", filename);
2702                 cdf_free(cdf);
2703                 return;
2704         }
2705
2706         for(i=0; i<data->totlayer; i++) {
2707                 layer = &data->layers[i];
2708                 typeInfo = layerType_getInfo(layer->type);
2709
2710                 if((layer->flag & CD_FLAG_EXTERNAL) && typeInfo->write) {
2711                         if(free) {
2712                                 if(typeInfo->free)
2713                                         typeInfo->free(layer->data, totelem, typeInfo->size);
2714                                 layer->flag &= ~CD_FLAG_IN_MEMORY;
2715                         }
2716                 }
2717         }
2718
2719         cdf_write_close(cdf);
2720         cdf_free(cdf);
2721 }
2722
2723 void CustomData_external_add(CustomData *data, ID *UNUSED(id), int type, int UNUSED(totelem), const char *filename)
2724 {
2725         CustomDataExternal *external= data->external;
2726         CustomDataLayer *layer;
2727         int layer_index;
2728
2729         layer_index = CustomData_get_active_layer_index(data, type);
2730         if(layer_index < 0) return;
2731
2732         layer = &data->layers[layer_index];
2733
2734         if(layer->flag & CD_FLAG_EXTERNAL)
2735                 return;
2736
2737         if(!external) {
2738                 external= MEM_callocN(sizeof(CustomDataExternal), "CustomDataExternal");
2739                 data->external= external;
2740         }
2741         BLI_strncpy(external->filename, filename, sizeof(external->filename));
2742
2743         layer->flag |= CD_FLAG_EXTERNAL|CD_FLAG_IN_MEMORY;
2744 }
2745
2746 void CustomData_external_remove(CustomData *data, ID *id, int type, int totelem)
2747 {
2748         CustomDataExternal *external= data->external;
2749         CustomDataLayer *layer;
2750         //char filename[FILE_MAX];
2751         int layer_index; // i, remove_file;
2752
2753         layer_index = CustomData_get_active_layer_index(data, type);
2754         if(layer_index < 0) return;
2755
2756         layer = &data->layers[layer_index];
2757
2758         if(!external)
2759                 return;
2760
2761         if(layer->flag & CD_FLAG_EXTERNAL) {
2762                 if(!(layer->flag & CD_FLAG_IN_MEMORY))
2763                         CustomData_external_read(data, id, CD_TYPE_AS_MASK(layer->type), totelem);
2764
2765                 layer->flag &= ~CD_FLAG_EXTERNAL;
2766
2767 #if 0
2768                 remove_file= 1;
2769                 for(i=0; i<data->totlayer; i++)
2770                         if(data->layers[i].flag & CD_FLAG_EXTERNAL)
2771                                 remove_file= 0;
2772
2773                 if(remove_file) {
2774                         customdata_external_filename(filename, id, external);
2775                         cdf_remove(filename);
2776                         CustomData_external_free(data);
2777                 }
2778 #endif
2779         }
2780 }
2781
2782 int CustomData_external_test(CustomData *data, int type)
2783 {
2784         CustomDataLayer *layer;
2785         int layer_index;
2786
2787         layer_index = CustomData_get_active_layer_index(data, type);
2788         if(layer_index < 0) return 0;
2789
2790         layer = &data->layers[layer_index];
2791         return (layer->flag & CD_FLAG_EXTERNAL);
2792 }
2793
2794 #if 0
2795 void CustomData_external_remove_object(CustomData *data, ID *id)
2796 {
2797         CustomDataExternal *external= data->external;
2798         char filename[FILE_MAX];
2799
2800         if(!external)
2801                 return;
2802
2803         customdata_external_filename(filename, id, external);
2804         cdf_remove(filename);
2805         CustomData_external_free(data);
2806 }
2807 #endif
2808