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