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