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