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