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