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