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