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