minor edits
[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
984 static void layerInterp_bweight(void **sources, float *weights,
985                                 float *UNUSED(sub_weights), int count, void *dest)
986 {
987         float *f = dest;
988         float **in = (float **)sources;
989         int i;
990         
991         if(count <= 0) return;
992
993         *f = 0.0f;
994
995         if (weights) {
996                 for(i = 0; i < count; ++i) {
997                         *f += *in[i] * weights[i];
998                 }
999         }
1000         else {
1001                 for(i = 0; i < count; ++i) {
1002                         *f += *in[i];
1003                 }
1004         }
1005 }
1006
1007 static void layerInterp_shapekey(void **sources, float *weights,
1008                                  float *UNUSED(sub_weights), int count, void *dest)
1009 {
1010         float *co = dest;
1011         float **in = (float **)sources;
1012         int i;
1013
1014         if(count <= 0) return;
1015
1016         zero_v3(co);
1017
1018         if (weights) {
1019                 for(i = 0; i < count; ++i) {
1020                         madd_v3_v3fl(co, in[i], weights[i]);
1021                 }
1022         }
1023         else {
1024                 for(i = 0; i < count; ++i) {
1025                         add_v3_v3(co, in[i]);
1026                 }
1027         }
1028 }
1029
1030 static const LayerTypeInfo LAYERTYPEINFO[CD_NUMTYPES] = {
1031         /* 0: CD_MVERT */
1032         {sizeof(MVert), "MVert", 1, NULL, NULL, NULL, NULL, NULL, NULL},
1033         /* 1: CD_MSTICKY */
1034         {sizeof(MSticky), "MSticky", 1, NULL, NULL, NULL, layerInterp_msticky, NULL,
1035          NULL},
1036         /* 2: CD_MDEFORMVERT */
1037         {sizeof(MDeformVert), "MDeformVert", 1, NULL, layerCopy_mdeformvert,
1038          layerFree_mdeformvert, layerInterp_mdeformvert, NULL, NULL},
1039         /* 3: CD_MEDGE */
1040         {sizeof(MEdge), "MEdge", 1, NULL, NULL, NULL, NULL, NULL, NULL},
1041         /* 4: CD_MFACE */
1042         {sizeof(MFace), "MFace", 1, NULL, NULL, NULL, NULL, NULL, NULL},
1043         /* 5: CD_MTFACE */
1044         {sizeof(MTFace), "MTFace", 1, "UVMap", layerCopy_tface, NULL,
1045          layerInterp_tface, layerSwap_tface, layerDefault_tface},
1046         /* 6: CD_MCOL */
1047         /* 4 MCol structs per face */
1048         {sizeof(MCol)*4, "MCol", 4, "Col", NULL, NULL, layerInterp_mcol,
1049          layerSwap_mcol, layerDefault_mcol},
1050         /* 7: CD_ORIGINDEX */
1051         {sizeof(int), "", 0, NULL, NULL, NULL, NULL, NULL, NULL},
1052         /* 8: CD_NORMAL */
1053         /* 3 floats per normal vector */
1054         {sizeof(float)*3, "vec3f", 1, NULL, NULL, NULL, NULL, NULL, NULL},
1055         /* 9: CD_POLYINDEX */
1056         {sizeof(int), "MIntProperty", 1, NULL, NULL, NULL, NULL, NULL, NULL},
1057         /* 10: CD_PROP_FLT */
1058         {sizeof(MFloatProperty), "MFloatProperty",1,"Float", layerCopy_propFloat,NULL,NULL,NULL},
1059         /* 11: CD_PROP_INT */
1060         {sizeof(MIntProperty), "MIntProperty",1,"Int",layerCopy_propInt,NULL,NULL,NULL},
1061         /* 12: CD_PROP_STR */
1062         {sizeof(MStringProperty), "MStringProperty",1,"String",layerCopy_propString,NULL,NULL,NULL},
1063         /* 13: CD_ORIGSPACE */
1064         {sizeof(OrigSpaceFace), "OrigSpaceFace", 1, "UVMap", layerCopy_origspace_face, NULL,
1065          layerInterp_origspace_face, layerSwap_origspace_face, layerDefault_origspace_face},
1066         /* 14: CD_ORCO */
1067         {sizeof(float)*3, "", 0, NULL, NULL, NULL, NULL, NULL, NULL},
1068         /* 15: CD_MTEXPOLY */
1069         {sizeof(MTexPoly), "MTexPoly", 1, "Face Texture", NULL, NULL, NULL, NULL, NULL},
1070         /* 16: CD_MLOOPUV */
1071         {sizeof(MLoopUV), "MLoopUV", 1, "UV coord", NULL, NULL, layerInterp_mloopuv, NULL, NULL,
1072          layerEqual_mloopuv, layerMultiply_mloopuv, layerInitMinMax_mloopuv, 
1073          layerAdd_mloopuv, layerDoMinMax_mloopuv, layerCopyValue_mloopuv},
1074         /* 17: CD_MLOOPCOL */
1075         {sizeof(MLoopCol), "MLoopCol", 1, "Col", NULL, NULL, layerInterp_mloopcol, NULL, 
1076          layerDefault_mloopcol, layerEqual_mloopcol, layerMultiply_mloopcol, layerInitMinMax_mloopcol, 
1077          layerAdd_mloopcol, layerDoMinMax_mloopcol, layerCopyValue_mloopcol},
1078         /* 18: CD_TANGENT */
1079         {sizeof(float)*4*4, "", 0, NULL, NULL, NULL, NULL, NULL, NULL},
1080         /* 19: CD_MDISPS */
1081         {sizeof(MDisps), "MDisps", 1, NULL, layerCopy_mdisps,
1082          layerFree_mdisps, layerInterp_mdisps, layerSwap_mdisps, NULL,
1083          NULL, NULL, NULL, NULL, NULL, NULL, 
1084          layerRead_mdisps, layerWrite_mdisps, layerFilesize_mdisps, layerValidate_mdisps},
1085         /* 20: CD_WEIGHT_MCOL */
1086         {sizeof(MCol)*4, "MCol", 4, "WeightCol", NULL, NULL, layerInterp_mcol,
1087          layerSwap_mcol, layerDefault_mcol},
1088         /* 21: CD_ID_MCOL */
1089         {sizeof(MCol)*4, "MCol", 4, "IDCol", NULL, NULL, layerInterp_mcol,
1090          layerSwap_mcol, layerDefault_mcol},
1091         /* 22: CD_TEXTURE_MCOL */
1092         {sizeof(MCol)*4, "MCol", 4, "TexturedCol", NULL, NULL, layerInterp_mcol,
1093          layerSwap_mcol, layerDefault_mcol},
1094         /* 23: CD_CLOTH_ORCO */
1095         {sizeof(float)*3, "", 0, NULL, NULL, NULL, NULL, NULL, NULL},
1096         /* 24: CD_RECAST */
1097         {sizeof(MRecast), "MRecast", 1,"Recast",NULL,NULL,NULL,NULL}
1098
1099 /* BMESH ONLY */
1100         ,
1101         /* 25: CD_MPOLY */
1102         {sizeof(MPoly), "MPoly", 1, "NGon Face", NULL, NULL, NULL, NULL, NULL},
1103         /* 26: CD_MLOOP */
1104         {sizeof(MLoop), "MLoop", 1, "NGon Face-Vertex", NULL, NULL, NULL, NULL, NULL},
1105         /* 27: CD_SHAPE_KEYINDEX */
1106         {sizeof(int), "", 0, NULL, NULL, NULL, NULL, NULL, NULL},
1107         /* 28: CD_SHAPEKEY */
1108         {sizeof(float)*3, "", 0, "ShapeKey", NULL, NULL, layerInterp_shapekey},
1109         /* 29: CD_BWEIGHT */
1110         {sizeof(float), "", 0, "BevelWeight", NULL, NULL, layerInterp_bweight},
1111         /* 30: CD_CREASE */
1112         {sizeof(float), "", 0, "SubSurfCrease", NULL, NULL, layerInterp_bweight},
1113         /* 31: CD_WEIGHT_MLOOPCOL */
1114         {sizeof(MLoopCol), "MLoopCol", 1, "WeightLoopCol", NULL, NULL, layerInterp_mloopcol, NULL,
1115          layerDefault_mloopcol, layerEqual_mloopcol, layerMultiply_mloopcol, layerInitMinMax_mloopcol,
1116          layerAdd_mloopcol, layerDoMinMax_mloopcol, layerCopyValue_mloopcol},
1117 /* END BMESH ONLY */
1118
1119
1120 };
1121
1122 /* note, numbers are from trunk and need updating for bmesh */
1123
1124 static const char *LAYERTYPENAMES[CD_NUMTYPES] = {
1125         /*   0-4 */ "CDMVert", "CDMSticky", "CDMDeformVert", "CDMEdge", "CDMFace",
1126         /*   5-9 */ "CDMTFace", "CDMCol", "CDOrigIndex", "CDNormal", "CDFlags",
1127         /* 10-14 */ "CDMFloatProperty", "CDMIntProperty","CDMStringProperty", "CDOrigSpace", "CDOrco",
1128         /* 15-19 */ "CDMTexPoly", "CDMLoopUV", "CDMloopCol", "CDTangent", "CDMDisps",
1129         /* 20-24 */"CDWeightMCol", "CDIDMCol", "CDTextureMCol", "CDClothOrco", "CDMRecast"
1130
1131 /* BMESH ONLY */
1132         ,
1133         /* 25-29 */ "CDMPoly", "CDMLoop", "CDShapeKeyIndex", "CDShapeKey", "CDBevelWeight",
1134         /* 30-31 */ "CDSubSurfCrease", "CDWeightLoopCol"
1135 /* END BMESH ONLY */
1136
1137 };
1138
1139
1140 const CustomDataMask CD_MASK_BAREMESH =
1141         CD_MASK_MVERT | CD_MASK_MEDGE | CD_MASK_MFACE | CD_MASK_MLOOP | CD_MASK_MPOLY | CD_MASK_BWEIGHT;
1142 const CustomDataMask CD_MASK_MESH =
1143         CD_MASK_MVERT | CD_MASK_MEDGE | CD_MASK_MFACE |
1144         CD_MASK_MSTICKY | CD_MASK_MDEFORMVERT | CD_MASK_MTFACE | CD_MASK_MCOL |
1145         CD_MASK_PROP_FLT | CD_MASK_PROP_INT | CD_MASK_PROP_STR | CD_MASK_MDISPS |
1146         CD_MASK_MLOOPUV | CD_MASK_MLOOPCOL | CD_MASK_MPOLY | CD_MASK_MLOOP |
1147         CD_MASK_MTEXPOLY | CD_MASK_NORMAL | CD_MASK_MDISPS | CD_MASK_RECAST;
1148 const CustomDataMask CD_MASK_EDITMESH =
1149         CD_MASK_MSTICKY | CD_MASK_MDEFORMVERT | CD_MASK_MTFACE | CD_MASK_MLOOPUV |
1150         CD_MASK_MLOOPCOL | CD_MASK_MTEXPOLY | CD_MASK_SHAPE_KEYINDEX |
1151         CD_MASK_MCOL|CD_MASK_PROP_FLT | CD_MASK_PROP_INT | CD_MASK_PROP_STR |
1152         CD_MASK_MDISPS | CD_MASK_SHAPEKEY | CD_MASK_RECAST;
1153 const CustomDataMask CD_MASK_DERIVEDMESH =
1154         CD_MASK_MSTICKY | CD_MASK_MDEFORMVERT | CD_MASK_MTFACE |
1155         CD_MASK_MCOL | CD_MASK_PROP_FLT | CD_MASK_PROP_INT | CD_MASK_CLOTH_ORCO |
1156         CD_MASK_MLOOPUV | CD_MASK_MLOOPCOL | CD_MASK_MTEXPOLY | CD_MASK_WEIGHT_MLOOPCOL |
1157         CD_MASK_PROP_STR | CD_MASK_ORIGSPACE | CD_MASK_ORCO | CD_MASK_TANGENT | 
1158         CD_MASK_WEIGHT_MCOL | CD_MASK_NORMAL | CD_MASK_SHAPEKEY | CD_MASK_RECAST |
1159         CD_MASK_ORIGINDEX | CD_MASK_POLYINDEX;
1160 const CustomDataMask CD_MASK_BMESH = CD_MASK_MLOOPUV | CD_MASK_MLOOPCOL | CD_MASK_MTEXPOLY |
1161         CD_MASK_MSTICKY | CD_MASK_MDEFORMVERT | CD_MASK_PROP_FLT | CD_MASK_PROP_INT | 
1162         CD_MASK_PROP_STR | CD_MASK_SHAPEKEY | CD_MASK_SHAPE_KEYINDEX | CD_MASK_MDISPS;
1163 const CustomDataMask CD_MASK_FACECORNERS =
1164         CD_MASK_MTFACE | CD_MASK_MCOL | CD_MASK_MTEXPOLY | CD_MASK_MLOOPUV |
1165         CD_MASK_MLOOPCOL;
1166
1167 static const LayerTypeInfo *layerType_getInfo(int type)
1168 {
1169         if(type < 0 || type >= CD_NUMTYPES) return NULL;
1170
1171         return &LAYERTYPEINFO[type];
1172 }
1173
1174 static const char *layerType_getName(int type)
1175 {
1176         if(type < 0 || type >= CD_NUMTYPES) return NULL;
1177
1178         return LAYERTYPENAMES[type];
1179 }
1180
1181 /********************* CustomData functions *********************/
1182 static void customData_update_offsets(CustomData *data);
1183
1184 static CustomDataLayer *customData_add_layer__internal(CustomData *data,
1185         int type, int alloctype, void *layerdata, int totelem, const char *name);
1186
1187 void CustomData_update_typemap(CustomData *data)
1188 {
1189         int i, lasttype = -1;
1190
1191         /* since we cant do in a pre-processor do here as an assert */
1192         BLI_assert(sizeof(data->typemap) / sizeof(int) >= CD_NUMTYPES);
1193
1194         for (i=0; i<CD_NUMTYPES; i++) {
1195                 data->typemap[i] = -1;
1196         }
1197
1198         for (i=0; i<data->totlayer; i++) {
1199                 if (data->layers[i].type != lasttype) {
1200                         data->typemap[data->layers[i].type] = i;
1201                 }
1202                 lasttype = data->layers[i].type;
1203         }
1204 }
1205
1206 void CustomData_merge(const struct CustomData *source, struct CustomData *dest,
1207                                           CustomDataMask mask, int alloctype, int totelem)
1208 {
1209         /*const LayerTypeInfo *typeInfo;*/
1210         CustomDataLayer *layer, *newlayer;
1211         void *data;
1212         int i, type, number = 0, lasttype = -1, lastactive = 0, lastrender = 0, lastclone = 0, lastmask = 0, lastflag = 0;
1213
1214         for(i = 0; i < source->totlayer; ++i) {
1215                 layer = &source->layers[i];
1216                 /*typeInfo = layerType_getInfo(layer->type);*/ /*UNUSED*/
1217
1218                 type = layer->type;
1219
1220                 if (type != lasttype) {
1221                         number = 0;
1222                         lastactive = layer->active;
1223                         lastrender = layer->active_rnd;
1224                         lastclone = layer->active_clone;
1225                         lastmask = layer->active_mask;
1226                         lasttype = type;
1227                         lastflag = layer->flag;
1228                 }
1229                 else
1230                         number++;
1231
1232                 if(lastflag & CD_FLAG_NOCOPY) continue;
1233                 else if(!(mask & CD_TYPE_AS_MASK(type))) continue;
1234                 else if(number < CustomData_number_of_layers(dest, type)) continue;
1235
1236                 switch (alloctype) {
1237                         case CD_ASSIGN:
1238                         case CD_REFERENCE:
1239                         case CD_DUPLICATE:
1240                                 data = layer->data;
1241                                 break;
1242                         default:
1243                                 data = NULL;
1244                                 break;
1245                 }
1246
1247                 if((alloctype == CD_ASSIGN) && (lastflag & CD_FLAG_NOFREE))
1248                         newlayer = customData_add_layer__internal(dest, type, CD_REFERENCE,
1249                                 data, totelem, layer->name);
1250                 else
1251                         newlayer = customData_add_layer__internal(dest, type, alloctype,
1252                                 data, totelem, layer->name);
1253                 
1254                 if(newlayer) {
1255                         newlayer->uid = layer->uid;
1256                         
1257                         newlayer->active = lastactive;
1258                         newlayer->active_rnd = lastrender;
1259                         newlayer->active_clone = lastclone;
1260                         newlayer->active_mask = lastmask;
1261                         newlayer->flag |= lastflag & (CD_FLAG_EXTERNAL|CD_FLAG_IN_MEMORY);
1262                 }
1263         }
1264
1265         CustomData_update_typemap(dest);
1266 }
1267
1268 void CustomData_copy(const struct CustomData *source, struct CustomData *dest,
1269                                          CustomDataMask mask, int alloctype, int totelem)
1270 {
1271         memset(dest, 0, sizeof(*dest));
1272
1273         if(source->external)
1274                 dest->external= MEM_dupallocN(source->external);
1275
1276         CustomData_merge(source, dest, mask, alloctype, totelem);
1277 }
1278
1279 static void customData_free_layer__internal(CustomDataLayer *layer, int totelem)
1280 {
1281         const LayerTypeInfo *typeInfo;
1282
1283         if(!(layer->flag & CD_FLAG_NOFREE) && layer->data) {
1284                 typeInfo = layerType_getInfo(layer->type);
1285
1286                 if(typeInfo->free)
1287                         typeInfo->free(layer->data, totelem, typeInfo->size);
1288
1289                 if(layer->data)
1290                         MEM_freeN(layer->data);
1291         }
1292 }
1293
1294 static void CustomData_external_free(CustomData *data)
1295 {
1296         if(data->external) {
1297                 MEM_freeN(data->external);
1298                 data->external= NULL;
1299         }
1300 }
1301
1302 void CustomData_free(CustomData *data, int totelem)
1303 {
1304         int i;
1305
1306         for(i = 0; i < data->totlayer; ++i)
1307                 customData_free_layer__internal(&data->layers[i], totelem);
1308
1309         if(data->layers)
1310                 MEM_freeN(data->layers);
1311         
1312         CustomData_external_free(data);
1313         
1314         memset(data, 0, sizeof(*data));
1315 }
1316
1317 static void customData_update_offsets(CustomData *data)
1318 {
1319         const LayerTypeInfo *typeInfo;
1320         int i, offset = 0;
1321
1322         for(i = 0; i < data->totlayer; ++i) {
1323                 typeInfo = layerType_getInfo(data->layers[i].type);
1324
1325                 data->layers[i].offset = offset;
1326                 offset += typeInfo->size;
1327         }
1328
1329         data->totsize = offset;
1330         CustomData_update_typemap(data);
1331 }
1332
1333 int CustomData_get_layer_index(const CustomData *data, int type)
1334 {
1335         int i; 
1336
1337         for(i=0; i < data->totlayer; ++i)
1338                 if(data->layers[i].type == type)
1339                         return i;
1340
1341         return -1;
1342 }
1343
1344 int CustomData_get_layer_index_n(const struct CustomData *data, int type, int n)
1345 {
1346         int i = CustomData_get_layer_index(data, type);
1347
1348         if (i != -1) {
1349                 i = (data->layers[i + n].type == type) ? (i + n) : (-1);
1350         }
1351
1352         return i;
1353 }
1354
1355 int CustomData_get_named_layer_index(const CustomData *data, int type, const char *name)
1356 {
1357         int i;
1358
1359         for(i=0; i < data->totlayer; ++i)
1360                 if(data->layers[i].type == type && strcmp(data->layers[i].name, name)==0)
1361                         return i;
1362
1363         return -1;
1364 }
1365
1366 int CustomData_get_active_layer_index(const CustomData *data, int type)
1367 {
1368         if (!data->totlayer)
1369                 return -1;
1370
1371         if (data->typemap[type] != -1) {
1372                 return data->typemap[type] + data->layers[data->typemap[type]].active;
1373         }
1374
1375         return -1;
1376 }
1377
1378 int CustomData_get_render_layer_index(const CustomData *data, int type)
1379 {
1380         int i;
1381
1382         for(i=0; i < data->totlayer; ++i)
1383                 if(data->layers[i].type == type)
1384                         return i + data->layers[i].active_rnd;
1385
1386         return -1;
1387 }
1388
1389 int CustomData_get_clone_layer_index(const CustomData *data, int type)
1390 {
1391         int i;
1392
1393         for(i=0; i < data->totlayer; ++i)
1394                 if(data->layers[i].type == type)
1395                         return i + data->layers[i].active_clone;
1396
1397         return -1;
1398 }
1399
1400 int CustomData_get_stencil_layer_index(const CustomData *data, int type)
1401 {
1402         int i;
1403
1404         for(i=0; i < data->totlayer; ++i)
1405                 if(data->layers[i].type == type)
1406                         return i + data->layers[i].active_mask;
1407
1408         return -1;
1409 }
1410
1411 int CustomData_get_active_layer(const CustomData *data, int type)
1412 {
1413         int i;
1414
1415         for(i=0; i < data->totlayer; ++i)
1416                 if(data->layers[i].type == type)
1417                         return data->layers[i].active;
1418
1419         return -1;
1420 }
1421
1422 int CustomData_get_render_layer(const CustomData *data, int type)
1423 {
1424         int i;
1425
1426         for(i=0; i < data->totlayer; ++i)
1427                 if(data->layers[i].type == type)
1428                         return data->layers[i].active_rnd;
1429
1430         return -1;
1431 }
1432
1433 int CustomData_get_clone_layer(const CustomData *data, int type)
1434 {
1435         int i;
1436
1437         for(i=0; i < data->totlayer; ++i)
1438                 if(data->layers[i].type == type)
1439                         return data->layers[i].active_clone;
1440
1441         return -1;
1442 }
1443
1444 int CustomData_get_stencil_layer(const CustomData *data, int type)
1445 {
1446         int i;
1447
1448         for(i=0; i < data->totlayer; ++i)
1449                 if(data->layers[i].type == type)
1450                         return data->layers[i].active_mask;
1451
1452         return -1;
1453 }
1454
1455 void CustomData_set_layer_active(CustomData *data, int type, int n)
1456 {
1457         int i;
1458
1459         for(i=0; i < data->totlayer; ++i)
1460                 if(data->layers[i].type == type)
1461                         data->layers[i].active = n;
1462 }
1463
1464 void CustomData_set_layer_render(CustomData *data, int type, int n)
1465 {
1466         int i;
1467
1468         for(i=0; i < data->totlayer; ++i)
1469                 if(data->layers[i].type == type)
1470                         data->layers[i].active_rnd = n;
1471 }
1472
1473 void CustomData_set_layer_clone(CustomData *data, int type, int n)
1474 {
1475         int i;
1476
1477         for(i=0; i < data->totlayer; ++i)
1478                 if(data->layers[i].type == type)
1479                         data->layers[i].active_clone = n;
1480 }
1481
1482 void CustomData_set_layer_stencil(CustomData *data, int type, int n)
1483 {
1484         int i;
1485
1486         for(i=0; i < data->totlayer; ++i)
1487                 if(data->layers[i].type == type)
1488                         data->layers[i].active_mask = n;
1489 }
1490
1491 /* for using with an index from CustomData_get_active_layer_index and CustomData_get_render_layer_index */
1492 void CustomData_set_layer_active_index(CustomData *data, int type, int n)
1493 {
1494         int i;
1495
1496         for(i=0; i < data->totlayer; ++i)
1497                 if(data->layers[i].type == type)
1498                         data->layers[i].active = n-i;
1499 }
1500
1501 void CustomData_set_layer_render_index(CustomData *data, int type, int n)
1502 {
1503         int i;
1504
1505         for(i=0; i < data->totlayer; ++i)
1506                 if(data->layers[i].type == type)
1507                         data->layers[i].active_rnd = n-i;
1508 }
1509
1510 void CustomData_set_layer_clone_index(CustomData *data, int type, int n)
1511 {
1512         int i;
1513
1514         for(i=0; i < data->totlayer; ++i)
1515                 if(data->layers[i].type == type)
1516                         data->layers[i].active_clone = n-i;
1517 }
1518
1519 void CustomData_set_layer_stencil_index(CustomData *data, int type, int n)
1520 {
1521         int i;
1522
1523         for(i=0; i < data->totlayer; ++i)
1524                 if(data->layers[i].type == type)
1525                         data->layers[i].active_mask = n-i;
1526 }
1527
1528 void CustomData_set_layer_flag(struct CustomData *data, int type, int flag)
1529 {
1530         int i;
1531
1532         for(i=0; i < data->totlayer; ++i)
1533                 if(data->layers[i].type == type)
1534                         data->layers[i].flag |= flag;
1535 }
1536
1537 static int customData_resize(CustomData *data, int amount)
1538 {
1539         CustomDataLayer *tmp = MEM_callocN(sizeof(*tmp)*(data->maxlayer + amount),
1540                                                                            "CustomData->layers");
1541         if(!tmp) return 0;
1542
1543         data->maxlayer += amount;
1544         if (data->layers) {
1545                 memcpy(tmp, data->layers, sizeof(*tmp) * data->totlayer);
1546                 MEM_freeN(data->layers);
1547         }
1548         data->layers = tmp;
1549
1550         return 1;
1551 }
1552
1553 static CustomDataLayer *customData_add_layer__internal(CustomData *data,
1554         int type, int alloctype, void *layerdata, int totelem, const char *name)
1555 {
1556         const LayerTypeInfo *typeInfo= layerType_getInfo(type);
1557         int size = typeInfo->size * totelem, flag = 0, index = data->totlayer;
1558         void *newlayerdata = NULL;
1559
1560         /* Passing a layerdata to copy from with an alloctype that won't copy is
1561            most likely a bug */
1562         BLI_assert(!layerdata ||
1563                    (alloctype == CD_ASSIGN) ||
1564                    (alloctype == CD_DUPLICATE) ||
1565                    (alloctype == CD_REFERENCE));
1566
1567         if (!typeInfo->defaultname && CustomData_has_layer(data, type))
1568                 return &data->layers[CustomData_get_layer_index(data, type)];
1569
1570         if((alloctype == CD_ASSIGN) || (alloctype == CD_REFERENCE)) {
1571                 newlayerdata = layerdata;
1572         }
1573         else if (size > 0) {
1574                 newlayerdata = MEM_callocN(size, layerType_getName(type));
1575                 if(!newlayerdata)
1576                         return NULL;
1577         }
1578
1579         if (alloctype == CD_DUPLICATE && layerdata) {
1580                 if(typeInfo->copy)
1581                         typeInfo->copy(layerdata, newlayerdata, totelem);
1582                 else
1583                         memcpy(newlayerdata, layerdata, size);
1584         }
1585         else if (alloctype == CD_DEFAULT) {
1586                 if(typeInfo->set_default)
1587                         typeInfo->set_default((char*)newlayerdata, totelem);
1588         }
1589         else if (alloctype == CD_REFERENCE)
1590                 flag |= CD_FLAG_NOFREE;
1591
1592         if(index >= data->maxlayer) {
1593                 if(!customData_resize(data, CUSTOMDATA_GROW)) {
1594                         if(newlayerdata != layerdata)
1595                                 MEM_freeN(newlayerdata);
1596                         return NULL;
1597                 }
1598         }
1599         
1600         data->totlayer++;
1601
1602         /* keep layers ordered by type */
1603         for( ; index > 0 && data->layers[index - 1].type > type; --index)
1604                 data->layers[index] = data->layers[index - 1];
1605
1606         data->layers[index].type = type;
1607         data->layers[index].flag = flag;
1608         data->layers[index].data = newlayerdata;
1609
1610         if(name || (name=typeInfo->defaultname)) {
1611                 BLI_strncpy(data->layers[index].name, name, 32);
1612                 CustomData_set_layer_unique_name(data, index);
1613         }
1614         else
1615                 data->layers[index].name[0] = '\0';
1616
1617         if(index > 0 && data->layers[index-1].type == type) {
1618                 data->layers[index].active = data->layers[index-1].active;
1619                 data->layers[index].active_rnd = data->layers[index-1].active_rnd;
1620                 data->layers[index].active_clone = data->layers[index-1].active_clone;
1621                 data->layers[index].active_mask = data->layers[index-1].active_mask;
1622         } else {
1623                 data->layers[index].active = 0;
1624                 data->layers[index].active_rnd = 0;
1625                 data->layers[index].active_clone = 0;
1626                 data->layers[index].active_mask = 0;
1627         }
1628         
1629         customData_update_offsets(data);
1630
1631         return &data->layers[index];
1632 }
1633
1634 void *CustomData_add_layer(CustomData *data, int type, int alloctype,
1635                                                    void *layerdata, int totelem)
1636 {
1637         CustomDataLayer *layer;
1638         const LayerTypeInfo *typeInfo= layerType_getInfo(type);
1639         
1640         layer = customData_add_layer__internal(data, type, alloctype, layerdata,
1641                                                                                    totelem, typeInfo->defaultname);
1642         CustomData_update_typemap(data);
1643
1644         if(layer)
1645                 return layer->data;
1646
1647         return NULL;
1648 }
1649
1650 /*same as above but accepts a name*/
1651 void *CustomData_add_layer_named(CustomData *data, int type, int alloctype,
1652                                                    void *layerdata, int totelem, const char *name)
1653 {
1654         CustomDataLayer *layer;
1655         
1656         layer = customData_add_layer__internal(data, type, alloctype, layerdata,
1657                                                                                    totelem, name);
1658         CustomData_update_typemap(data);
1659
1660         if(layer)
1661                 return layer->data;
1662
1663         return NULL;
1664 }
1665
1666
1667 int CustomData_free_layer(CustomData *data, int type, int totelem, int index)
1668 {
1669         int i;
1670         
1671         if (index < 0) return 0;
1672
1673         customData_free_layer__internal(&data->layers[index], totelem);
1674
1675         for (i=index+1; i < data->totlayer; ++i)
1676                 data->layers[i-1] = data->layers[i];
1677
1678         data->totlayer--;
1679
1680         /* if layer was last of type in array, set new active layer */
1681         if ((index >= data->totlayer) || (data->layers[index].type != type)) {
1682                 i = CustomData_get_layer_index(data, type);
1683                 
1684                 if (i >= 0)
1685                         for (; i < data->totlayer && data->layers[i].type == type; i++) {
1686                                 data->layers[i].active--;
1687                                 data->layers[i].active_rnd--;
1688                                 data->layers[i].active_clone--;
1689                                 data->layers[i].active_mask--;
1690                         }
1691         }
1692
1693         if (data->totlayer <= data->maxlayer-CUSTOMDATA_GROW)
1694                 customData_resize(data, -CUSTOMDATA_GROW);
1695
1696         customData_update_offsets(data);
1697         CustomData_update_typemap(data);
1698
1699         return 1;
1700 }
1701
1702 int CustomData_free_layer_active(CustomData *data, int type, int totelem)
1703 {
1704         int index = 0;
1705         index = CustomData_get_active_layer_index(data, type);
1706         if (index < 0) return 0;
1707         return CustomData_free_layer(data, type, totelem, index);
1708 }
1709
1710
1711 void CustomData_free_layers(CustomData *data, int type, int totelem)
1712 {
1713         while (CustomData_has_layer(data, type))
1714                 CustomData_free_layer_active(data, type, totelem);
1715 }
1716
1717 int CustomData_has_layer(const CustomData *data, int type)
1718 {
1719         return (CustomData_get_layer_index(data, type) != -1);
1720 }
1721
1722 int CustomData_number_of_layers(const CustomData *data, int type)
1723 {
1724         int i, number = 0;
1725
1726         for(i = 0; i < data->totlayer; i++)
1727                 if(data->layers[i].type == type)
1728                         number++;
1729         
1730         return number;
1731 }
1732
1733 void *CustomData_duplicate_referenced_layer(struct CustomData *data, const int type, const int totelem)
1734 {
1735         CustomDataLayer *layer;
1736         int layer_index;
1737
1738         /* get the layer index of the first layer of type */
1739         layer_index = CustomData_get_active_layer_index(data, type);
1740         if(layer_index < 0) return NULL;
1741
1742         layer = &data->layers[layer_index];
1743
1744         if (layer->flag & CD_FLAG_NOFREE) {
1745                 /* MEM_dupallocN won’t work in case of complex layers, like e.g.
1746                  * CD_MDEFORMVERT, which has pointers to allocated data...
1747                  * So in case a custom copy function is defined, use it!
1748                  */
1749                 const LayerTypeInfo *typeInfo = layerType_getInfo(layer->type);
1750
1751                 if(typeInfo->copy) {
1752                         char *dest_data = MEM_mallocN(typeInfo->size * totelem, "CD duplicate ref layer");
1753                         typeInfo->copy(layer->data, dest_data, totelem);
1754                         layer->data = dest_data;
1755                 }
1756                 else
1757                         layer->data = MEM_dupallocN(layer->data);
1758
1759                 layer->flag &= ~CD_FLAG_NOFREE;
1760         }
1761
1762         return layer->data;
1763 }
1764
1765 void *CustomData_duplicate_referenced_layer_named(struct CustomData *data,
1766                                                                                                   const int type, const char *name, const int totelem)
1767 {
1768         CustomDataLayer *layer;
1769         int layer_index;
1770
1771         /* get the layer index of the desired layer */
1772         layer_index = CustomData_get_named_layer_index(data, type, name);
1773         if(layer_index < 0) return NULL;
1774
1775         layer = &data->layers[layer_index];
1776
1777         if (layer->flag & CD_FLAG_NOFREE) {
1778                 /* MEM_dupallocN won’t work in case of complex layers, like e.g.
1779                  * CD_MDEFORMVERT, which has pointers to allocated data...
1780                  * So in case a custom copy function is defined, use it!
1781                  */
1782                 const LayerTypeInfo *typeInfo = layerType_getInfo(layer->type);
1783
1784                 if(typeInfo->copy) {
1785                         char *dest_data = MEM_mallocN(typeInfo->size * totelem, "CD duplicate ref layer");
1786                         typeInfo->copy(layer->data, dest_data, totelem);
1787                         layer->data = dest_data;
1788                 }
1789                 else
1790                         layer->data = MEM_dupallocN(layer->data);
1791
1792                 layer->flag &= ~CD_FLAG_NOFREE;
1793         }
1794
1795         return layer->data;
1796 }
1797
1798 int CustomData_is_referenced_layer(struct CustomData *data, int type)
1799 {
1800         CustomDataLayer *layer;
1801         int layer_index;
1802
1803         /* get the layer index of the first layer of type */
1804         layer_index = CustomData_get_active_layer_index(data, type);
1805         if(layer_index < 0) return 0;
1806
1807         layer = &data->layers[layer_index];
1808
1809         return (layer->flag & CD_FLAG_NOFREE) != 0;
1810 }
1811
1812 void CustomData_free_temporary(CustomData *data, int totelem)
1813 {
1814         CustomDataLayer *layer;
1815         int i, j;
1816
1817         for(i = 0, j = 0; i < data->totlayer; ++i) {
1818                 layer = &data->layers[i];
1819
1820                 if (i != j)
1821                         data->layers[j] = data->layers[i];
1822
1823                 if ((layer->flag & CD_FLAG_TEMPORARY) == CD_FLAG_TEMPORARY)
1824                         customData_free_layer__internal(layer, totelem);
1825                 else
1826                         j++;
1827         }
1828
1829         data->totlayer = j;
1830
1831         if(data->totlayer <= data->maxlayer-CUSTOMDATA_GROW)
1832                 customData_resize(data, -CUSTOMDATA_GROW);
1833
1834         customData_update_offsets(data);
1835 }
1836
1837 void CustomData_set_only_copy(const struct CustomData *data,
1838                               CustomDataMask mask)
1839 {
1840         int i;
1841
1842         for(i = 0; i < data->totlayer; ++i)
1843                 if(!(mask & CD_TYPE_AS_MASK(data->layers[i].type)))
1844                         data->layers[i].flag |= CD_FLAG_NOCOPY;
1845 }
1846
1847 void CustomData_copy_elements(int type, void *source, void *dest, int count)
1848 {
1849         const LayerTypeInfo *typeInfo = layerType_getInfo(type);
1850
1851         if (typeInfo->copy)
1852                 typeInfo->copy(source, dest, count);
1853         else
1854                 memcpy(dest, source, typeInfo->size*count);
1855 }
1856
1857 void CustomData_copy_data(const CustomData *source, CustomData *dest,
1858                                                   int source_index, int dest_index, int count)
1859 {
1860         const LayerTypeInfo *typeInfo;
1861         int src_i, dest_i;
1862         int src_offset;
1863         int dest_offset;
1864
1865         /* copies a layer at a time */
1866         dest_i = 0;
1867         for(src_i = 0; src_i < source->totlayer; ++src_i) {
1868
1869                 /* find the first dest layer with type >= the source type
1870                  * (this should work because layers are ordered by type)
1871                  */
1872                 while(dest_i < dest->totlayer
1873                           && dest->layers[dest_i].type < source->layers[src_i].type)
1874                         ++dest_i;
1875
1876                 /* if there are no more dest layers, we're done */
1877                 if(dest_i >= dest->totlayer) return;
1878
1879                 /* if we found a matching layer, copy the data */
1880                 if(dest->layers[dest_i].type == source->layers[src_i].type) {
1881                         char *src_data = source->layers[src_i].data;
1882                         char *dest_data = dest->layers[dest_i].data;
1883
1884                         typeInfo = layerType_getInfo(source->layers[src_i].type);
1885
1886                         src_offset = source_index * typeInfo->size;
1887                         dest_offset = dest_index * typeInfo->size;
1888                         
1889                         if (!src_data || !dest_data) {
1890                                 printf("%s: warning null data for %s type (%p --> %p), skipping\n",
1891                                        __func__, layerType_getName(source->layers[src_i].type),
1892                                        (void *)src_data, (void *)dest_data);
1893                                 continue;
1894                         }
1895                         
1896                         if(typeInfo->copy)
1897                                 typeInfo->copy(src_data + src_offset,
1898                                                                 dest_data + dest_offset,
1899                                                                 count);
1900                         else
1901                                 memcpy(dest_data + dest_offset,
1902                                            src_data + src_offset,
1903                                            count * typeInfo->size);
1904
1905                         /* if there are multiple source & dest layers of the same type,
1906                          * we don't want to copy all source layers to the same dest, so
1907                          * increment dest_i
1908                          */
1909                         ++dest_i;
1910                 }
1911         }
1912 }
1913
1914 void CustomData_free_elem(CustomData *data, int index, int count)
1915 {
1916         int i;
1917         const LayerTypeInfo *typeInfo;
1918
1919         for(i = 0; i < data->totlayer; ++i) {
1920                 if(!(data->layers[i].flag & CD_FLAG_NOFREE)) {
1921                         typeInfo = layerType_getInfo(data->layers[i].type);
1922
1923                         if(typeInfo->free) {
1924                                 int offset = typeInfo->size * index;
1925
1926                                 typeInfo->free((char *)data->layers[i].data + offset,
1927                                                            count, typeInfo->size);
1928                         }
1929                 }
1930         }
1931 }
1932
1933 #define SOURCE_BUF_SIZE 100
1934
1935 void CustomData_interp(const CustomData *source, CustomData *dest,
1936                                            int *src_indices, float *weights, float *sub_weights,
1937                                            int count, int dest_index)
1938 {
1939         int src_i, dest_i;
1940         int dest_offset;
1941         int j;
1942         void *source_buf[SOURCE_BUF_SIZE];
1943         void **sources = source_buf;
1944
1945         /* slow fallback in case we're interpolating a ridiculous number of
1946          * elements
1947          */
1948         if(count > SOURCE_BUF_SIZE)
1949                 sources = MEM_callocN(sizeof(*sources) * count,
1950                                                           "CustomData_interp sources");
1951
1952         /* interpolates a layer at a time */
1953         dest_i = 0;
1954         for(src_i = 0; src_i < source->totlayer; ++src_i) {
1955                 const LayerTypeInfo *typeInfo= layerType_getInfo(source->layers[src_i].type);
1956                 if(!typeInfo->interp) continue;
1957
1958                 /* find the first dest layer with type >= the source type
1959                  * (this should work because layers are ordered by type)
1960                  */
1961                 while(dest_i < dest->totlayer
1962                           && dest->layers[dest_i].type < source->layers[src_i].type)
1963                         ++dest_i;
1964
1965                 /* if there are no more dest layers, we're done */
1966                 if(dest_i >= dest->totlayer) return;
1967
1968                 /* if we found a matching layer, copy the data */
1969                 if(dest->layers[dest_i].type == source->layers[src_i].type) {
1970                         void *src_data = source->layers[src_i].data;
1971
1972                         for(j = 0; j < count; ++j)
1973                                 sources[j] = (char *)src_data
1974                                                          + typeInfo->size * src_indices[j];
1975
1976                         dest_offset = dest_index * typeInfo->size;
1977
1978                         typeInfo->interp(sources, weights, sub_weights, count,
1979                                                    (char *)dest->layers[dest_i].data + dest_offset);
1980
1981                         /* if there are multiple source & dest layers of the same type,
1982                          * we don't want to copy all source layers to the same dest, so
1983                          * increment dest_i
1984                          */
1985                         ++dest_i;
1986                 }
1987         }
1988
1989         if(count > SOURCE_BUF_SIZE) MEM_freeN(sources);
1990 }
1991
1992 void CustomData_swap(struct CustomData *data, int index, const int *corner_indices)
1993 {
1994         const LayerTypeInfo *typeInfo;
1995         int i;
1996
1997         for(i = 0; i < data->totlayer; ++i) {
1998                 typeInfo = layerType_getInfo(data->layers[i].type);
1999
2000                 if(typeInfo->swap) {
2001                         int offset = typeInfo->size * index;
2002
2003                         typeInfo->swap((char *)data->layers[i].data + offset, corner_indices);
2004                 }
2005         }
2006 }
2007
2008 void *CustomData_get(const CustomData *data, int index, int type)
2009 {
2010         int offset;
2011         int layer_index;
2012         
2013         /* get the layer index of the active layer of type */
2014         layer_index = CustomData_get_active_layer_index(data, type);
2015         if(layer_index < 0) return NULL;
2016
2017         /* get the offset of the desired element */
2018         offset = layerType_getInfo(type)->size * index;
2019
2020         return (char *)data->layers[layer_index].data + offset;
2021 }
2022
2023 void *CustomData_get_n(const CustomData *data, int type, int index, int n)
2024 {
2025         int layer_index;
2026         int offset;
2027
2028         /* get the layer index of the first layer of type */
2029         layer_index = data->typemap[type];
2030         if(layer_index < 0) return NULL;
2031
2032         offset = layerType_getInfo(type)->size * index;
2033         return (char *)data->layers[layer_index+n].data + offset;
2034 }
2035
2036 void *CustomData_get_layer(const CustomData *data, int type)
2037 {
2038         /* get the layer index of the active layer of type */
2039         int layer_index = CustomData_get_active_layer_index(data, type);
2040         if(layer_index < 0) return NULL;
2041
2042         return data->layers[layer_index].data;
2043 }
2044
2045 void *CustomData_get_layer_n(const CustomData *data, int type, int n)
2046 {
2047         /* get the layer index of the active layer of type */
2048         int layer_index = CustomData_get_layer_index_n(data, type, n);
2049         if(layer_index < 0) return NULL;
2050
2051         return data->layers[layer_index].data;
2052 }
2053
2054 void *CustomData_get_layer_named(const struct CustomData *data, int type,
2055                                                                  const char *name)
2056 {
2057         int layer_index = CustomData_get_named_layer_index(data, type, name);
2058         if(layer_index < 0) return NULL;
2059
2060         return data->layers[layer_index].data;
2061 }
2062
2063
2064 int CustomData_set_layer_name(const CustomData *data, int type, int n, const char *name)
2065 {
2066         /* get the layer index of the first layer of type */
2067         int layer_index = CustomData_get_layer_index_n(data, type, n);
2068
2069         if(layer_index < 0) return 0;
2070         if (!name) return 0;
2071         
2072         strcpy(data->layers[layer_index].name, name);
2073         
2074         return 1;
2075 }
2076
2077 void *CustomData_set_layer(const CustomData *data, int type, void *ptr)
2078 {
2079         /* get the layer index of the first layer of type */
2080         int layer_index = CustomData_get_active_layer_index(data, type);
2081
2082         if(layer_index < 0) return NULL;
2083
2084         data->layers[layer_index].data = ptr;
2085
2086         return ptr;
2087 }
2088
2089 void *CustomData_set_layer_n(const struct CustomData *data, int type, int n, void *ptr)
2090 {
2091         /* get the layer index of the first layer of type */
2092         int layer_index = CustomData_get_layer_index_n(data, type, n);
2093         if(layer_index < 0) return NULL;
2094
2095         data->layers[layer_index].data = ptr;
2096
2097         return ptr;
2098 }
2099
2100 void CustomData_set(const CustomData *data, int index, int type, void *source)
2101 {
2102         void *dest = CustomData_get(data, index, type);
2103         const LayerTypeInfo *typeInfo = layerType_getInfo(type);
2104
2105         if(!dest) return;
2106
2107         if(typeInfo->copy)
2108                 typeInfo->copy(source, dest, 1);
2109         else
2110                 memcpy(dest, source, typeInfo->size);
2111 }
2112
2113 /* EditMesh functions */
2114
2115 void CustomData_em_free_block(CustomData *data, void **block)
2116 {
2117         const LayerTypeInfo *typeInfo;
2118         int i;
2119
2120         if(!*block) return;
2121
2122         for(i = 0; i < data->totlayer; ++i) {
2123                 if(!(data->layers[i].flag & CD_FLAG_NOFREE)) {
2124                         typeInfo = layerType_getInfo(data->layers[i].type);
2125
2126                         if(typeInfo->free) {
2127                                 int offset = data->layers[i].offset;
2128                                 typeInfo->free((char*)*block + offset, 1, typeInfo->size);
2129                         }
2130                 }
2131         }
2132
2133         MEM_freeN(*block);
2134         *block = NULL;
2135 }
2136
2137 static void CustomData_em_alloc_block(CustomData *data, void **block)
2138 {
2139         /* TODO: optimize free/alloc */
2140
2141         if (*block)
2142                 CustomData_em_free_block(data, block);
2143
2144         if (data->totsize > 0)
2145                 *block = MEM_callocN(data->totsize, "CustomData EM block");
2146         else
2147                 *block = NULL;
2148 }
2149
2150 void CustomData_em_copy_data(const CustomData *source, CustomData *dest,
2151                                                         void *src_block, void **dest_block)
2152 {
2153         const LayerTypeInfo *typeInfo;
2154         int dest_i, src_i;
2155
2156         if (!*dest_block)
2157                 CustomData_em_alloc_block(dest, dest_block);
2158         
2159         /* copies a layer at a time */
2160         dest_i = 0;
2161         for(src_i = 0; src_i < source->totlayer; ++src_i) {
2162
2163                 /* find the first dest layer with type >= the source type
2164                  * (this should work because layers are ordered by type)
2165                  */
2166                 while(dest_i < dest->totlayer
2167                           && dest->layers[dest_i].type < source->layers[src_i].type)
2168                         ++dest_i;
2169
2170                 /* if there are no more dest layers, we're done */
2171                 if(dest_i >= dest->totlayer) return;
2172
2173                 /* if we found a matching layer, copy the data */
2174                 if(dest->layers[dest_i].type == source->layers[src_i].type &&
2175                         strcmp(dest->layers[dest_i].name, source->layers[src_i].name) == 0) {
2176                         char *src_data = (char*)src_block + source->layers[src_i].offset;
2177                         char *dest_data = (char*)*dest_block + dest->layers[dest_i].offset;
2178
2179                         typeInfo = layerType_getInfo(source->layers[src_i].type);
2180
2181                         if(typeInfo->copy)
2182                                 typeInfo->copy(src_data, dest_data, 1);
2183                         else
2184                                 memcpy(dest_data, src_data, typeInfo->size);
2185
2186                         /* if there are multiple source & dest layers of the same type,
2187                          * we don't want to copy all source layers to the same dest, so
2188                          * increment dest_i
2189                          */
2190                         ++dest_i;
2191                 }
2192         }
2193 }
2194
2195 void CustomData_em_validate_data(CustomData *data, void *block, int sub_elements)
2196 {
2197         int i;
2198         for(i = 0; i < data->totlayer; i++) {
2199                 const LayerTypeInfo *typeInfo = layerType_getInfo(data->layers[i].type);
2200                 char *leayer_data = (char*)block + data->layers[i].offset;
2201
2202                 if(typeInfo->validate)
2203                         typeInfo->validate(leayer_data, sub_elements);
2204         }
2205 }
2206
2207 void *CustomData_em_get(const CustomData *data, void *block, int type)
2208 {
2209         int layer_index;
2210         
2211         /* get the layer index of the first layer of type */
2212         layer_index = CustomData_get_active_layer_index(data, type);
2213         if(layer_index < 0) return NULL;
2214
2215         return (char *)block + data->layers[layer_index].offset;
2216 }
2217
2218 void *CustomData_em_get_n(const CustomData *data, void *block, int type, int n)
2219 {
2220         int layer_index;
2221         
2222         /* get the layer index of the first layer of type */
2223         layer_index = CustomData_get_layer_index_n(data, type, n);
2224         if(layer_index < 0) return NULL;
2225
2226         return (char *)block + data->layers[layer_index].offset;
2227 }
2228
2229 void CustomData_em_set(CustomData *data, void *block, int type, void *source)
2230 {
2231         void *dest = CustomData_em_get(data, block, type);
2232         const LayerTypeInfo *typeInfo = layerType_getInfo(type);
2233
2234         if(!dest) return;
2235
2236         if(typeInfo->copy)
2237                 typeInfo->copy(source, dest, 1);
2238         else
2239                 memcpy(dest, source, typeInfo->size);
2240 }
2241
2242 void CustomData_em_set_n(CustomData *data, void *block, int type, int n, void *source)
2243 {
2244         void *dest = CustomData_em_get_n(data, block, type, n);
2245         const LayerTypeInfo *typeInfo = layerType_getInfo(type);
2246
2247         if(!dest) return;
2248
2249         if(typeInfo->copy)
2250                 typeInfo->copy(source, dest, 1);
2251         else
2252                 memcpy(dest, source, typeInfo->size);
2253 }
2254
2255 void CustomData_em_interp(CustomData *data, void **src_blocks, float *weights,
2256                                                   float *sub_weights, int count, void *dest_block)
2257 {
2258         int i, j;
2259         void *source_buf[SOURCE_BUF_SIZE];
2260         void **sources = source_buf;
2261
2262         /* slow fallback in case we're interpolating a ridiculous number of
2263          * elements
2264          */
2265         if(count > SOURCE_BUF_SIZE)
2266                 sources = MEM_callocN(sizeof(*sources) * count,
2267                                                           "CustomData_interp sources");
2268
2269         /* interpolates a layer at a time */
2270         for(i = 0; i < data->totlayer; ++i) {
2271                 CustomDataLayer *layer = &data->layers[i];
2272                 const LayerTypeInfo *typeInfo = layerType_getInfo(layer->type);
2273
2274                 if(typeInfo->interp) {
2275                         for(j = 0; j < count; ++j)
2276                                 sources[j] = (char *)src_blocks[j] + layer->offset;
2277
2278                         typeInfo->interp(sources, weights, sub_weights, count,
2279                                                           (char *)dest_block + layer->offset);
2280                 }
2281         }
2282
2283         if(count > SOURCE_BUF_SIZE) MEM_freeN(sources);
2284 }
2285
2286 void CustomData_em_set_default(CustomData *data, void **block)
2287 {
2288         const LayerTypeInfo *typeInfo;
2289         int i;
2290
2291         if (!*block)
2292                 CustomData_em_alloc_block(data, block);
2293
2294         for(i = 0; i < data->totlayer; ++i) {
2295                 int offset = data->layers[i].offset;
2296
2297                 typeInfo = layerType_getInfo(data->layers[i].type);
2298
2299                 if(typeInfo->set_default)
2300                         typeInfo->set_default((char*)*block + offset, 1);
2301         }
2302 }
2303
2304 void CustomData_to_em_block(const CustomData *source, CustomData *dest,
2305                                                         int src_index, void **dest_block)
2306 {
2307         const LayerTypeInfo *typeInfo;
2308         int dest_i, src_i, src_offset;
2309
2310         if (!*dest_block)
2311                 CustomData_em_alloc_block(dest, dest_block);
2312         
2313         /* copies a layer at a time */
2314         dest_i = 0;
2315         for(src_i = 0; src_i < source->totlayer; ++src_i) {
2316
2317                 /* find the first dest layer with type >= the source type
2318                  * (this should work because layers are ordered by type)
2319                  */
2320                 while(dest_i < dest->totlayer
2321                           && dest->layers[dest_i].type < source->layers[src_i].type)
2322                         ++dest_i;
2323
2324                 /* if there are no more dest layers, we're done */
2325                 if(dest_i >= dest->totlayer) return;
2326
2327                 /* if we found a matching layer, copy the data */
2328                 if(dest->layers[dest_i].type == source->layers[src_i].type) {
2329                         int offset = dest->layers[dest_i].offset;
2330                         char *src_data = source->layers[src_i].data;
2331                         char *dest_data = (char*)*dest_block + offset;
2332
2333                         typeInfo = layerType_getInfo(dest->layers[dest_i].type);
2334                         src_offset = src_index * typeInfo->size;
2335
2336                         if(typeInfo->copy)
2337                                 typeInfo->copy(src_data + src_offset, dest_data, 1);
2338                         else
2339                                 memcpy(dest_data, src_data + src_offset, typeInfo->size);
2340
2341                         /* if there are multiple source & dest layers of the same type,
2342                          * we don't want to copy all source layers to the same dest, so
2343                          * increment dest_i
2344                          */
2345                         ++dest_i;
2346                 }
2347         }
2348 }
2349
2350 void CustomData_from_em_block(const CustomData *source, CustomData *dest,
2351                                                           void *src_block, int dest_index)
2352 {
2353         const LayerTypeInfo *typeInfo;
2354         int dest_i, src_i, dest_offset;
2355
2356         /* copies a layer at a time */
2357         dest_i = 0;
2358         for(src_i = 0; src_i < source->totlayer; ++src_i) {
2359
2360                 /* find the first dest layer with type >= the source type
2361                  * (this should work because layers are ordered by type)
2362                  */
2363                 while(dest_i < dest->totlayer
2364                           && dest->layers[dest_i].type < source->layers[src_i].type)
2365                         ++dest_i;
2366
2367                 /* if there are no more dest layers, we're done */
2368                 if(dest_i >= dest->totlayer) return;
2369
2370                 /* if we found a matching layer, copy the data */
2371                 if(dest->layers[dest_i].type == source->layers[src_i].type) {
2372                         int offset = source->layers[src_i].offset;
2373                         char *src_data = (char*)src_block + offset;
2374                         char *dest_data = dest->layers[dest_i].data;
2375
2376                         typeInfo = layerType_getInfo(dest->layers[dest_i].type);
2377                         dest_offset = dest_index * typeInfo->size;
2378
2379                         if(typeInfo->copy)
2380                                 typeInfo->copy(src_data, dest_data + dest_offset, 1);
2381                         else
2382                                 memcpy(dest_data + dest_offset, src_data, typeInfo->size);
2383
2384                         /* if there are multiple source & dest layers of the same type,
2385                          * we don't want to copy all source layers to the same dest, so
2386                          * increment dest_i
2387                          */
2388                         ++dest_i;
2389                 }
2390         }
2391
2392 }
2393
2394 /*Bmesh functions*/
2395 /*needed to convert to/from different face reps*/
2396 void CustomData_to_bmeshpoly(CustomData *fdata, CustomData *pdata, CustomData *ldata,
2397                              int totloop, int totpoly)
2398 {
2399         int i;
2400         for(i=0; i < fdata->totlayer; i++) {
2401                 if(fdata->layers[i].type == CD_MTFACE) {
2402                         CustomData_add_layer_named(pdata, CD_MTEXPOLY, CD_CALLOC, NULL, totpoly, fdata->layers[i].name);
2403                         CustomData_add_layer_named(ldata, CD_MLOOPUV, CD_CALLOC, NULL, totloop, fdata->layers[i].name);
2404                 }
2405                 else if (fdata->layers[i].type == CD_MCOL) {
2406                         CustomData_add_layer_named(ldata, CD_MLOOPCOL, CD_CALLOC, NULL, totloop, fdata->layers[i].name);
2407                 }
2408                 else if (fdata->layers[i].type == CD_MDISPS) {
2409                         CustomData_add_layer_named(ldata, CD_MDISPS, CD_CALLOC, NULL, totloop, fdata->layers[i].name);
2410                 }
2411         }
2412 }
2413
2414 void CustomData_from_bmeshpoly(CustomData *fdata, CustomData *pdata, CustomData *ldata, int total)
2415 {
2416         int i;
2417         for(i=0; i < pdata->totlayer; i++) {
2418                 if (pdata->layers[i].type == CD_MTEXPOLY) {
2419                         CustomData_add_layer_named(fdata, CD_MTFACE, CD_CALLOC, NULL, total, pdata->layers[i].name);
2420                 }
2421         }
2422         for(i=0; i < ldata->totlayer; i++) {
2423                 if (ldata->layers[i].type == CD_MLOOPCOL) {
2424                         CustomData_add_layer_named(fdata, CD_MCOL, CD_CALLOC, NULL, total, ldata->layers[i].name);
2425                 }
2426                 else if (ldata->layers[i].type == CD_WEIGHT_MLOOPCOL) {
2427                         CustomData_add_layer_named(fdata, CD_WEIGHT_MCOL, CD_CALLOC, NULL, total, ldata->layers[i].name);
2428                 }
2429         }
2430 }
2431
2432 void CustomData_bmesh_update_active_layers(CustomData *fdata, CustomData *pdata, CustomData *ldata)
2433 {
2434         int act;
2435
2436         if (CustomData_has_layer(pdata, CD_MTEXPOLY)) {
2437                 act = CustomData_get_active_layer(pdata, CD_MTEXPOLY);
2438                 CustomData_set_layer_active(ldata, CD_MLOOPUV, act);
2439                 CustomData_set_layer_active(fdata, CD_MTFACE, act);
2440
2441                 act = CustomData_get_render_layer(pdata, CD_MTEXPOLY);
2442                 CustomData_set_layer_render(ldata, CD_MLOOPUV, act);
2443                 CustomData_set_layer_render(fdata, CD_MTFACE, act);
2444
2445                 act = CustomData_get_clone_layer(pdata, CD_MTEXPOLY);
2446                 CustomData_set_layer_clone(ldata, CD_MLOOPUV, act);
2447                 CustomData_set_layer_clone(fdata, CD_MTFACE, act);
2448
2449                 act = CustomData_get_stencil_layer(pdata, CD_MTEXPOLY);
2450                 CustomData_set_layer_stencil(ldata, CD_MLOOPUV, act);
2451                 CustomData_set_layer_stencil(fdata, CD_MTFACE, act);
2452         }
2453
2454         if (CustomData_has_layer(ldata, CD_MLOOPCOL)) {
2455                 act = CustomData_get_active_layer(ldata, CD_MLOOPCOL);
2456                 CustomData_set_layer_active(fdata, CD_MCOL, act);
2457
2458                 act = CustomData_get_render_layer(ldata, CD_MLOOPCOL);
2459                 CustomData_set_layer_render(fdata, CD_MCOL, act);
2460
2461                 act = CustomData_get_clone_layer(ldata, CD_MLOOPCOL);
2462                 CustomData_set_layer_clone(fdata, CD_MCOL, act);
2463
2464                 act = CustomData_get_stencil_layer(ldata, CD_MLOOPCOL);
2465                 CustomData_set_layer_stencil(fdata, CD_MCOL, act);
2466         }
2467 }
2468
2469 void CustomData_bmesh_init_pool(CustomData *data, int allocsize)
2470 {
2471         /* Dispose old pools before calling here to avoid leaks */
2472         BLI_assert(data->pool == NULL);
2473
2474         /* If there are no layers, no pool is needed just yet */
2475         if (data->totlayer) {
2476                 data->pool = BLI_mempool_create(data->totsize, allocsize, allocsize, TRUE, FALSE);
2477         }
2478 }
2479
2480 void CustomData_bmesh_merge(CustomData *source, CustomData *dest, 
2481                             int mask, int alloctype, BMesh *bm, int type)
2482 {
2483         BMHeader *h;
2484         BMIter iter;
2485         CustomData destold = *dest;
2486         void *tmp;
2487         int t;
2488         
2489         CustomData_merge(source, dest, mask, alloctype, 0);
2490         CustomData_bmesh_init_pool(dest, 512);
2491
2492         switch (type) {
2493                 case BM_VERT:
2494                         t = BM_VERTS_OF_MESH; break;
2495                 case BM_EDGE:
2496                         t = BM_EDGES_OF_MESH; break;
2497                 case BM_LOOP:
2498                         t = BM_LOOPS_OF_FACE; break;
2499                 case BM_FACE:
2500                         t = BM_FACES_OF_MESH; break;
2501                 default: /* should never happen */
2502                         BLI_assert(!"invalid type given");
2503                         t = BM_VERTS_OF_MESH;
2504         }
2505
2506         if (t != BM_LOOPS_OF_FACE) {
2507                 /*ensure all current elements follow new customdata layout*/
2508                 BM_ITER(h, &iter, bm, t, NULL) {
2509                         CustomData_bmesh_copy_data(&destold, dest, h->data, &tmp);
2510                         CustomData_bmesh_free_block(&destold, &h->data);
2511                         h->data = tmp;
2512                 }
2513         } else {
2514                 BMFace *f;
2515                 BMLoop *l;
2516                 BMIter liter;
2517
2518                 /*ensure all current elements follow new customdata layout*/
2519                 BM_ITER(f, &iter, bm, BM_FACES_OF_MESH, NULL) {
2520                         BM_ITER(l, &liter, bm, BM_LOOPS_OF_FACE, f) {
2521                                 CustomData_bmesh_copy_data(&destold, dest, l->head.data, &tmp);
2522                                 CustomData_bmesh_free_block(&destold, &l->head.data);
2523                                 l->head.data = tmp;
2524                         }
2525                 }
2526         }
2527
2528         if (destold.pool) BLI_mempool_destroy(destold.pool);
2529 }
2530
2531 void CustomData_bmesh_free_block(CustomData *data, void **block)
2532 {
2533         const LayerTypeInfo *typeInfo;
2534         int i;
2535
2536         if(!*block) return;
2537         for(i = 0; i < data->totlayer; ++i) {
2538                 if(!(data->layers[i].flag & CD_FLAG_NOFREE)) {
2539                         typeInfo = layerType_getInfo(data->layers[i].type);
2540
2541                         if(typeInfo->free) {
2542                                 int offset = data->layers[i].offset;
2543                                 typeInfo->free((char*)*block + offset, 1, typeInfo->size);
2544                         }
2545                 }
2546         }
2547
2548         if (data->totsize)
2549                 BLI_mempool_free(data->pool, *block);
2550
2551         *block = NULL;
2552 }
2553
2554 static void CustomData_bmesh_alloc_block(CustomData *data, void **block)
2555 {
2556
2557         if (*block)
2558                 CustomData_bmesh_free_block(data, block);
2559
2560         if (data->totsize > 0)
2561                 *block = BLI_mempool_alloc(data->pool);
2562         else
2563                 *block = NULL;
2564 }
2565
2566 void CustomData_bmesh_copy_data(const CustomData *source, CustomData *dest,
2567                                                         void *src_block, void **dest_block)
2568 {
2569         const LayerTypeInfo *typeInfo;
2570         int dest_i, src_i;
2571
2572         if (!*dest_block)
2573                 CustomData_bmesh_alloc_block(dest, dest_block);
2574         
2575         /* copies a layer at a time */
2576         dest_i = 0;
2577         for(src_i = 0; src_i < source->totlayer; ++src_i) {
2578
2579                 /* find the first dest layer with type >= the source type
2580                  * (this should work because layers are ordered by type)
2581                  */
2582                 while(dest_i < dest->totlayer
2583                           && dest->layers[dest_i].type < source->layers[src_i].type)
2584                         ++dest_i;
2585
2586                 /* if there are no more dest layers, we're done */
2587                 if(dest_i >= dest->totlayer) return;
2588
2589                 /* if we found a matching layer, copy the data */
2590                 if(dest->layers[dest_i].type == source->layers[src_i].type &&
2591                         strcmp(dest->layers[dest_i].name, source->layers[src_i].name) == 0) {
2592                         char *src_data = (char*)src_block + source->layers[src_i].offset;
2593                         char *dest_data = (char*)*dest_block + dest->layers[dest_i].offset;
2594
2595                         typeInfo = layerType_getInfo(source->layers[src_i].type);
2596
2597                         if(typeInfo->copy)
2598                                 typeInfo->copy(src_data, dest_data, 1);
2599                         else
2600                                 memcpy(dest_data, src_data, typeInfo->size);
2601
2602                         /* if there are multiple source & dest layers of the same type,
2603                          * we don't want to copy all source layers to the same dest, so
2604                          * increment dest_i
2605                          */
2606                         ++dest_i;
2607                 }
2608         }
2609 }
2610
2611 /*Bmesh Custom Data Functions. Should replace editmesh ones with these as well, due to more effecient memory alloc*/
2612 void *CustomData_bmesh_get(const CustomData *data, void *block, int type)
2613 {
2614         int layer_index;
2615         
2616         /* get the layer index of the first layer of type */
2617         layer_index = CustomData_get_active_layer_index(data, type);
2618         if(layer_index < 0) return NULL;
2619
2620         return (char *)block + data->layers[layer_index].offset;
2621 }
2622
2623 void *CustomData_bmesh_get_n(const CustomData *data, void *block, int type, int n)
2624 {
2625         int layer_index;
2626         
2627         /* get the layer index of the first layer of type */
2628         layer_index = CustomData_get_layer_index(data, type);
2629         if(layer_index < 0) return NULL;
2630
2631         return (char *)block + data->layers[layer_index+n].offset;
2632 }
2633
2634 /*gets from the layer at physical index n, note: doesn't check type.*/
2635 void *CustomData_bmesh_get_layer_n(const CustomData *data, void *block, int n)
2636 {
2637         if(n < 0 || n >= data->totlayer) return NULL;
2638
2639         return (char *)block + data->layers[n].offset;
2640 }
2641
2642 int CustomData_layer_has_math(struct CustomData *data, int layern)
2643 {
2644         const LayerTypeInfo *typeInfo = layerType_getInfo(data->layers[layern].type);
2645         
2646         if (typeInfo->equal && typeInfo->add && typeInfo->multiply && 
2647             typeInfo->initminmax && typeInfo->dominmax) return 1;
2648         
2649         return 0;
2650 }
2651
2652 /*copies the "value" (e.g. mloopuv uv or mloopcol colors) from one block to
2653   another, while not overwriting anything else (e.g. flags)*/
2654 void CustomData_data_copy_value(int type, void *source, void *dest)
2655 {
2656         const LayerTypeInfo *typeInfo = layerType_getInfo(type);
2657
2658         if(!dest) return;
2659
2660         if(typeInfo->copyvalue)
2661                 typeInfo->copyvalue(source, dest);
2662         else
2663                 memcpy(dest, source, typeInfo->size);
2664 }
2665
2666 int CustomData_data_equals(int type, void *data1, void *data2)
2667 {
2668         const LayerTypeInfo *typeInfo = layerType_getInfo(type);
2669
2670         if (typeInfo->equal)
2671                 return typeInfo->equal(data1, data2);
2672         else return !memcmp(data1, data2, typeInfo->size);
2673 }
2674
2675 void CustomData_data_initminmax(int type, void *min, void *max)
2676 {
2677         const LayerTypeInfo *typeInfo = layerType_getInfo(type);
2678
2679         if (typeInfo->initminmax)
2680                 typeInfo->initminmax(min, max);
2681 }
2682
2683
2684 void CustomData_data_dominmax(int type, void *data, void *min, void *max)
2685 {
2686         const LayerTypeInfo *typeInfo = layerType_getInfo(type);
2687
2688         if (typeInfo->dominmax)
2689                 typeInfo->dominmax(data, min, max);
2690 }
2691
2692
2693 void CustomData_data_multiply(int type, void *data, float fac)
2694 {
2695         const LayerTypeInfo *typeInfo = layerType_getInfo(type);
2696
2697         if (typeInfo->multiply)
2698                 typeInfo->multiply(data, fac);
2699 }
2700
2701
2702 void CustomData_data_add(int type, void *data1, void *data2)
2703 {
2704         const LayerTypeInfo *typeInfo = layerType_getInfo(type);
2705
2706         if (typeInfo->add)
2707                 typeInfo->add(data1, data2);
2708 }
2709
2710 void CustomData_bmesh_set(const CustomData *data, void *block, int type, void *source)
2711 {
2712         void *dest = CustomData_bmesh_get(data, block, type);
2713         const LayerTypeInfo *typeInfo = layerType_getInfo(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_set_n(CustomData *data, void *block, int type, int n, void *source)
2724 {
2725         void *dest = CustomData_bmesh_get_n(data, block, type, n);
2726         const LayerTypeInfo *typeInfo = layerType_getInfo(type);
2727
2728         if(!dest) return;
2729
2730         if(typeInfo->copy)
2731                 typeInfo->copy(source, dest, 1);
2732         else
2733                 memcpy(dest, source, typeInfo->size);
2734 }
2735
2736 void CustomData_bmesh_set_layer_n(CustomData *data, void *block, int n, void *source)
2737 {
2738         void *dest = CustomData_bmesh_get_layer_n(data, block, n);
2739         const LayerTypeInfo *typeInfo = layerType_getInfo(data->layers[n].type);
2740
2741         if(!dest) return;
2742
2743         if(typeInfo->copy)
2744                 typeInfo->copy(source, dest, 1);
2745         else
2746                 memcpy(dest, source, typeInfo->size);
2747 }
2748
2749 void CustomData_bmesh_interp(CustomData *data, void **src_blocks, float *weights,
2750                                                   float *sub_weights, int count, void *dest_block)
2751 {
2752         int i, j;
2753         void *source_buf[SOURCE_BUF_SIZE];
2754         void **sources = source_buf;
2755
2756         /* slow fallback in case we're interpolating a ridiculous number of
2757          * elements
2758          */
2759         if(count > SOURCE_BUF_SIZE)
2760                 sources = MEM_callocN(sizeof(*sources) * count,
2761                                                           "CustomData_interp sources");
2762
2763         /* interpolates a layer at a time */
2764         for(i = 0; i < data->totlayer; ++i) {
2765                 CustomDataLayer *layer = &data->layers[i];
2766                 const LayerTypeInfo *typeInfo = layerType_getInfo(layer->type);
2767                 if(typeInfo->interp) {
2768                         for(j = 0; j < count; ++j)
2769                                 sources[j] = (char *)src_blocks[j] + layer->offset;
2770
2771                         typeInfo->interp(sources, weights, sub_weights, count,
2772                                                           (char *)dest_block + layer->offset);
2773                 }
2774         }
2775
2776         if(count > SOURCE_BUF_SIZE) MEM_freeN(sources);
2777 }
2778
2779 void CustomData_bmesh_set_default(CustomData *data, void **block)
2780 {
2781         const LayerTypeInfo *typeInfo;
2782         int i;
2783
2784         if (!*block)
2785                 CustomData_bmesh_alloc_block(data, block);
2786
2787         for(i = 0; i < data->totlayer; ++i) {
2788                 int offset = data->layers[i].offset;
2789
2790                 typeInfo = layerType_getInfo(data->layers[i].type);
2791
2792                 if(typeInfo->set_default)
2793                         typeInfo->set_default((char*)*block + offset, 1);
2794                 else memset((char*)*block + offset, 0, typeInfo->size);
2795         }
2796 }
2797
2798 void CustomData_to_bmesh_block(const CustomData *source, CustomData *dest,
2799                                                         int src_index, void **dest_block)
2800 {
2801         const LayerTypeInfo *typeInfo;
2802         int dest_i, src_i, src_offset;
2803
2804         if (!*dest_block)
2805                 CustomData_bmesh_alloc_block(dest, dest_block);
2806         
2807         /* copies a layer at a time */
2808         dest_i = 0;
2809         for(src_i = 0; src_i < source->totlayer; ++src_i) {
2810
2811                 /* find the first dest layer with type >= the source type
2812                  * (this should work because layers are ordered by type)
2813                  */
2814                 while(dest_i < dest->totlayer
2815                           && dest->layers[dest_i].type < source->layers[src_i].type)
2816                         ++dest_i;
2817
2818                 /* if there are no more dest layers, we're done */
2819                 if(dest_i >= dest->totlayer) return;
2820
2821                 /* if we found a matching layer, copy the data */
2822                 if(dest->layers[dest_i].type == source->layers[src_i].type) {
2823                         int offset = dest->layers[dest_i].offset;
2824                         char *src_data = source->layers[src_i].data;
2825                         char *dest_data = (char*)*dest_block + offset;
2826
2827                         typeInfo = layerType_getInfo(dest->layers[dest_i].type);
2828                         src_offset = src_index * typeInfo->size;
2829
2830                         if(typeInfo->copy)
2831                                 typeInfo->copy(src_data + src_offset, dest_data, 1);
2832                         else
2833                                 memcpy(dest_data, src_data + src_offset, typeInfo->size);
2834
2835                         /* if there are multiple source & dest layers of the same type,
2836                          * we don't want to copy all source layers to the same dest, so
2837                          * increment dest_i
2838                          */
2839                         ++dest_i;
2840                 }
2841         }
2842 }
2843
2844 void CustomData_from_bmesh_block(const CustomData *source, CustomData *dest,
2845                                                           void *src_block, int dest_index)
2846 {
2847         const LayerTypeInfo *typeInfo;
2848         int dest_i, src_i, dest_offset;
2849
2850         /* copies a layer at a time */
2851         dest_i = 0;
2852         for(src_i = 0; src_i < source->totlayer; ++src_i) {
2853
2854                 /* find the first dest layer with type >= the source type
2855                  * (this should work because layers are ordered by type)
2856                  */
2857                 while(dest_i < dest->totlayer
2858                           && dest->layers[dest_i].type < source->layers[src_i].type)
2859                         ++dest_i;
2860
2861                 /* if there are no more dest layers, we're done */
2862                 if(dest_i >= dest->totlayer) return;
2863
2864                 /* if we found a matching layer, copy the data */
2865                 if(dest->layers[dest_i].type == source->layers[src_i].type) {
2866                         int offset = source->layers[src_i].offset;
2867                         char *src_data = (char*)src_block + offset;
2868                         char *dest_data = dest->layers[dest_i].data;
2869
2870                         typeInfo = layerType_getInfo(dest->layers[dest_i].type);
2871                         dest_offset = dest_index * typeInfo->size;
2872
2873                         if(typeInfo->copy)
2874                                 typeInfo->copy(src_data, dest_data + dest_offset, 1);
2875                         else
2876                                 memcpy(dest_data + dest_offset, src_data, typeInfo->size);
2877
2878                         /* if there are multiple source & dest layers of the same type,
2879                          * we don't want to copy all source layers to the same dest, so
2880                          * increment dest_i
2881                          */
2882                         ++dest_i;
2883                 }
2884         }
2885
2886 }
2887
2888 void CustomData_file_write_info(int type, const char **structname, int *structnum)
2889 {
2890         const LayerTypeInfo *typeInfo = layerType_getInfo(type);
2891
2892         *structname = typeInfo->structname;
2893         *structnum = typeInfo->structnum;
2894 }
2895
2896 int CustomData_sizeof(int type)
2897 {
2898         const LayerTypeInfo *typeInfo = layerType_getInfo(type);
2899
2900         return typeInfo->size;
2901 }
2902
2903 const char *CustomData_layertype_name(int type)
2904 {
2905         return layerType_getName(type);
2906 }
2907
2908 static int  CustomData_is_property_layer(int type)
2909 {
2910         if((type == CD_PROP_FLT) || (type == CD_PROP_INT) || (type == CD_PROP_STR))
2911                 return 1;
2912         return 0;
2913 }
2914
2915 static int cd_layer_find_dupe(CustomData *data, const char *name, int type, int index)
2916 {
2917         int i;
2918         /* see if there is a duplicate */
2919         for(i=0; i<data->totlayer; i++) {
2920                 if(i != index) {
2921                         CustomDataLayer *layer= &data->layers[i];
2922                         
2923                         if(CustomData_is_property_layer(type)) {
2924                                 if(CustomData_is_property_layer(layer->type) && strcmp(layer->name, name)==0) {
2925                                         return 1;
2926                                 }
2927                         }
2928                         else{
2929                                 if(i!=index && layer->type==type && strcmp(layer->name, name)==0) {
2930                                         return 1;
2931                                 }
2932                         }
2933                 }
2934         }
2935         
2936         return 0;
2937 }
2938
2939 static int customdata_unique_check(void *arg, const char *name)
2940 {
2941         struct {CustomData *data; int type; int index;} *data_arg= arg;
2942         return cd_layer_find_dupe(data_arg->data, name, data_arg->type, data_arg->index);
2943 }
2944
2945 void CustomData_set_layer_unique_name(CustomData *data, int index)
2946 {       
2947         CustomDataLayer *nlayer= &data->layers[index];
2948         const LayerTypeInfo *typeInfo= layerType_getInfo(nlayer->type);
2949
2950         struct {CustomData *data; int type; int index;} data_arg;
2951         data_arg.data= data;
2952         data_arg.type= nlayer->type;
2953         data_arg.index= index;
2954
2955         if (!typeInfo->defaultname)
2956                 return;
2957         
2958         BLI_uniquename_cb(customdata_unique_check, &data_arg, typeInfo->defaultname, '.', nlayer->name, sizeof(nlayer->name));
2959 }
2960
2961 void CustomData_validate_layer_name(const CustomData *data, int type, char *name, char *outname)
2962 {
2963         int index = -1;
2964
2965         /* if a layer name was given, try to find that layer */
2966         if(name[0])
2967                 index = CustomData_get_named_layer_index(data, type, name);
2968
2969         if(index < 0) {
2970                 /* either no layer was specified, or the layer we want has been
2971                 * deleted, so assign the active layer to name
2972                 */
2973                 index = CustomData_get_active_layer_index(data, type);
2974                 strcpy(outname, data->layers[index].name);
2975         }
2976         else
2977                 strcpy(outname, name);
2978 }
2979
2980 int CustomData_verify_versions(struct CustomData *data, int index)
2981 {
2982         const LayerTypeInfo *typeInfo;
2983         CustomDataLayer *layer = &data->layers[index];
2984         int i, keeplayer = 1;
2985
2986         if (layer->type >= CD_NUMTYPES) {
2987                 keeplayer = 0; /* unknown layer type from future version */
2988         }
2989         else {
2990                 typeInfo = layerType_getInfo(layer->type);
2991
2992                 if (!typeInfo->defaultname && (index > 0) &&
2993                         data->layers[index-1].type == layer->type)
2994                         keeplayer = 0; /* multiple layers of which we only support one */
2995         }
2996
2997         if (!keeplayer) {
2998                 for (i=index+1; i < data->totlayer; ++i)
2999                         data->layers[i-1] = data->layers[i];
3000                 data->totlayer--;
3001         }
3002
3003         return keeplayer;
3004 }
3005
3006 /****************************** External Files *******************************/
3007
3008 static void customdata_external_filename(char filename[FILE_MAX], ID *id, CustomDataExternal *external)
3009 {
3010         BLI_strncpy(filename, external->filename, FILE_MAX);
3011         BLI_path_abs(filename, ID_BLEND_PATH(G.main, id));
3012 }
3013
3014 void CustomData_external_reload(CustomData *data, ID *UNUSED(id), CustomDataMask mask, int totelem)
3015 {
3016         CustomDataLayer *layer;
3017         const LayerTypeInfo *typeInfo;
3018         int i;
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_EXTERNAL) && (layer->flag & CD_FLAG_IN_MEMORY)) {
3026                         if(typeInfo->free)
3027                                 typeInfo->free(layer->data, totelem, typeInfo->size);
3028                         layer->flag &= ~CD_FLAG_IN_MEMORY;
3029                 }
3030         }
3031 }
3032
3033 void CustomData_external_read(CustomData *data, ID *id, CustomDataMask mask, int totelem)
3034 {
3035         CustomDataExternal *external= data->external;
3036         CustomDataLayer *layer;
3037         CDataFile *cdf;
3038         CDataFileLayer *blay;
3039         char filename[FILE_MAX];
3040         const LayerTypeInfo *typeInfo;
3041         int i, update = 0;
3042
3043         if(!external)
3044                 return;
3045         
3046         for(i=0; i<data->totlayer; i++) {
3047                 layer = &data->layers[i];
3048                 typeInfo = layerType_getInfo(layer->type);
3049
3050                 if(!(mask & CD_TYPE_AS_MASK(layer->type)));
3051                 else if(layer->flag & CD_FLAG_IN_MEMORY);
3052                 else if((layer->flag & CD_FLAG_EXTERNAL) && typeInfo->read)
3053                         update= 1;
3054         }
3055
3056         if(!update)
3057                 return;
3058
3059         customdata_external_filename(filename, id, external);
3060
3061         cdf= cdf_create(CDF_TYPE_MESH);
3062         if(!cdf_read_open(cdf, filename)) {
3063                 fprintf(stderr, "Failed to read %s layer from %s.\n", layerType_getName(layer->type), filename);
3064                 return;
3065         }
3066
3067         for(i=0; i<data->totlayer; i++) {
3068                 layer = &data->layers[i];
3069                 typeInfo = layerType_getInfo(layer->type);
3070
3071                 if(!(mask & CD_TYPE_AS_MASK(layer->type)));
3072                 else if(layer->flag & CD_FLAG_IN_MEMORY);
3073                 else if((layer->flag & CD_FLAG_EXTERNAL) && typeInfo->read) {
3074                         blay= cdf_layer_find(cdf, layer->type, layer->name);
3075
3076                         if(blay) {
3077                                 if(cdf_read_layer(cdf, blay)) {
3078                                         if(typeInfo->read(cdf, layer->data, totelem));
3079                                         else break;
3080                                         layer->flag |= CD_FLAG_IN_MEMORY;
3081                                 }
3082                                 else
3083                                         break;
3084                         }
3085                 }
3086         }
3087
3088         cdf_read_close(cdf);
3089         cdf_free(cdf);
3090 }
3091
3092 void CustomData_external_write(CustomData *data, ID *id, CustomDataMask mask, int totelem, int free)
3093 {
3094         CustomDataExternal *external= data->external;
3095         CustomDataLayer *layer;
3096         CDataFile *cdf;
3097         CDataFileLayer *blay;
3098         const LayerTypeInfo *typeInfo;
3099         int i, update = 0;
3100         char filename[FILE_MAX];
3101
3102         if(!external)
3103                 return;
3104
3105         /* test if there is anything to write */
3106         for(i=0; i<data->totlayer; i++) {
3107                 layer = &data->layers[i];
3108                 typeInfo = layerType_getInfo(layer->type);
3109
3110                 if(!(mask & CD_TYPE_AS_MASK(layer->type)));
3111                 else if((layer->flag & CD_FLAG_EXTERNAL) && typeInfo->write)
3112                         update= 1;
3113         }
3114
3115         if(!update)
3116                 return;
3117
3118         /* make sure data is read before we try to write */
3119         CustomData_external_read(data, id, mask, totelem);
3120         customdata_external_filename(filename, id, external);
3121
3122         cdf= cdf_create(CDF_TYPE_MESH);
3123
3124         for(i=0; i<data->totlayer; i++) {
3125                 layer = &data->layers[i];
3126                 typeInfo = layerType_getInfo(layer->type);
3127
3128                 if((layer->flag & CD_FLAG_EXTERNAL) && typeInfo->filesize) {
3129                         if(layer->flag & CD_FLAG_IN_MEMORY) {
3130                                 cdf_layer_add(cdf, layer->type, layer->name,
3131                                         typeInfo->filesize(cdf, layer->data, totelem));
3132                         }
3133                         else {
3134                                 cdf_free(cdf);
3135                                 return; /* read failed for a layer! */
3136                         }
3137                 }
3138         }
3139
3140         if(!cdf_write_open(cdf, filename)) {
3141                 fprintf(stderr, "Failed to open %s for writing.\n", filename);
3142                 return;
3143         }
3144
3145         for(i=0; i<data->totlayer; i++) {
3146                 layer = &data->layers[i];
3147                 typeInfo = layerType_getInfo(layer->type);
3148
3149                 if((layer->flag & CD_FLAG_EXTERNAL) && typeInfo->write) {
3150                         blay= cdf_layer_find(cdf, layer->type, layer->name);
3151
3152                         if(cdf_write_layer(cdf, blay)) {
3153                                 if(typeInfo->write(cdf, layer->data, totelem));
3154                                 else break;
3155                         }
3156                         else
3157                                 break;
3158                 }
3159         }
3160
3161         if(i != data->totlayer) {
3162                 fprintf(stderr, "Failed to write data to %s.\n", filename);
3163                 cdf_free(cdf);
3164                 return;
3165         }
3166
3167         for(i=0; i<data->totlayer; i++) {
3168                 layer = &data->layers[i];
3169                 typeInfo = layerType_getInfo(layer->type);
3170
3171                 if((layer->flag & CD_FLAG_EXTERNAL) && typeInfo->write) {
3172                         if(free) {
3173                                 if(typeInfo->free)
3174                                         typeInfo->free(layer->data, totelem, typeInfo->size);
3175                                 layer->flag &= ~CD_FLAG_IN_MEMORY;
3176                         }
3177                 }
3178         }
3179
3180         cdf_write_close(cdf);
3181         cdf_free(cdf);
3182 }
3183
3184 void CustomData_external_add(CustomData *data, ID *UNUSED(id), int type, int UNUSED(totelem), const char *filename)
3185 {
3186         CustomDataExternal *external= data->external;
3187         CustomDataLayer *layer;
3188         int layer_index;
3189
3190         layer_index = CustomData_get_active_layer_index(data, type);
3191         if(layer_index < 0) return;
3192
3193         layer = &data->layers[layer_index];
3194
3195         if(layer->flag & CD_FLAG_EXTERNAL)
3196                 return;
3197
3198         if(!external) {
3199                 external= MEM_callocN(sizeof(CustomDataExternal), "CustomDataExternal");
3200                 data->external= external;
3201         }
3202         BLI_strncpy(external->filename, filename, sizeof(external->filename));
3203
3204         layer->flag |= CD_FLAG_EXTERNAL|CD_FLAG_IN_MEMORY;
3205 }
3206
3207 void CustomData_external_remove(CustomData *data,&nb