RNA:
[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_blenlib.h"
48 #include "BLI_linklist.h"
49 #include "BLI_math.h"
50 #include "BLI_mempool.h"
51 #include "BLI_utildefines.h"
52
53 #include "BKE_customdata.h"
54 #include "BKE_customdata_file.h"
55 #include "BKE_global.h"
56 #include "BKE_main.h"
57 #include "BKE_utildefines.h"
58 #include "BKE_multires.h"
59
60 /* number of layers to add when growing a CustomData object */
61 #define CUSTOMDATA_GROW 5
62
63 /********************* Layer type information **********************/
64 typedef struct LayerTypeInfo {
65         int size;          /* the memory size of one element of this layer's data */
66         const char *structname;  /* name of the struct used, for file writing */
67         int structnum;     /* number of structs per element, for file writing */
68         const char *defaultname; /* default layer name */
69
70         /* a function to copy count elements of this layer's data
71          * (deep copy if appropriate)
72          * if NULL, memcpy is used
73          */
74         void (*copy)(const void *source, void *dest, int count);
75
76         /* a function to free any dynamically allocated components of this
77          * layer's data (note the data pointer itself should not be freed)
78          * size should be the size of one element of this layer's data (e.g.
79          * LayerTypeInfo.size)
80          */
81         void (*free)(void *data, int count, int size);
82
83         /* a function to interpolate between count source elements of this
84          * layer's data and store the result in dest
85          * if weights == NULL or sub_weights == NULL, they should default to 1
86          *
87          * weights gives the weight for each element in sources
88          * sub_weights gives the sub-element weights for each element in sources
89          *    (there should be (sub element count)^2 weights per element)
90          * count gives the number of elements in sources
91          */
92         void (*interp)(void **sources, float *weights, float *sub_weights,
93                                    int count, void *dest);
94
95         /* a function to swap the data in corners of the element */
96         void (*swap)(void *data, const int *corner_indices);
97
98         /* a function to set a layer's data to default values. if NULL, the
99            default is assumed to be all zeros */
100         void (*set_default)(void *data, int count);
101
102         /* a function to read data from a cdf file */
103         int (*read)(CDataFile *cdf, void *data, int count);
104
105         /* a function to write data to a cdf file */
106         int (*write)(CDataFile *cdf, void *data, int count);
107
108         /* a function to determine file size */
109         size_t (*filesize)(CDataFile *cdf, void *data, int count);
110
111         /* a function to validate layer contents depending on
112          * sub-elements count
113          */
114         void (*validate)(void *source, int sub_elements);
115 } LayerTypeInfo;
116
117 static void layerCopy_mdeformvert(const void *source, void *dest,
118                                                                   int count)
119 {
120         int i, size = sizeof(MDeformVert);
121
122         memcpy(dest, source, count * size);
123
124         for(i = 0; i < count; ++i) {
125                 MDeformVert *dvert = (MDeformVert *)((char *)dest + i * size);
126
127                 if(dvert->totweight) {
128                         MDeformWeight *dw = MEM_callocN(dvert->totweight * sizeof(*dw),
129                                                                                         "layerCopy_mdeformvert dw");
130
131                         memcpy(dw, dvert->dw, dvert->totweight * sizeof(*dw));
132                         dvert->dw = dw;
133                 }
134                 else
135                         dvert->dw = NULL;
136         }
137 }
138
139 static void layerFree_mdeformvert(void *data, int count, int size)
140 {
141         int i;
142
143         for(i = 0; i < count; ++i) {
144                 MDeformVert *dvert = (MDeformVert *)((char *)data + i * size);
145
146                 if(dvert->dw) {
147                         MEM_freeN(dvert->dw);
148                         dvert->dw = NULL;
149                         dvert->totweight = 0;
150                 }
151         }
152 }
153
154 static void linklist_free_simple(void *link)
155 {
156         MEM_freeN(link);
157 }
158
159 static void layerInterp_mdeformvert(void **sources, float *weights,
160                                                                         float *UNUSED(sub_weights), int count, void *dest)
161 {
162         MDeformVert *dvert = dest;
163         LinkNode *dest_dw = NULL; /* a list of lists of MDeformWeight pointers */
164         LinkNode *node;
165         int i, j, totweight;
166
167         if(count <= 0) return;
168
169         /* build a list of unique def_nrs for dest */
170         totweight = 0;
171         for(i = 0; i < count; ++i) {
172                 MDeformVert *source = sources[i];
173                 float interp_weight = weights ? weights[i] : 1.0f;
174
175                 for(j = 0; j < source->totweight; ++j) {
176                         MDeformWeight *dw = &source->dw[j];
177
178                         for(node = dest_dw; node; node = node->next) {
179                                 MDeformWeight *tmp_dw = (MDeformWeight *)node->link;
180
181                                 if(tmp_dw->def_nr == dw->def_nr) {
182                                         tmp_dw->weight += dw->weight * interp_weight;
183                                         break;
184                                 }
185                         }
186
187                         /* if this def_nr is not in the list, add it */
188                         if(!node) {
189                                 MDeformWeight *tmp_dw = MEM_callocN(sizeof(*tmp_dw),
190                                                                                         "layerInterp_mdeformvert tmp_dw");
191                                 tmp_dw->def_nr = dw->def_nr;
192                                 tmp_dw->weight = dw->weight * interp_weight;
193                                 BLI_linklist_prepend(&dest_dw, tmp_dw);
194                                 totweight++;
195                         }
196                 }
197         }
198
199         /* now we know how many unique deform weights there are, so realloc */
200         if(dvert->dw) MEM_freeN(dvert->dw);
201
202         if(totweight) {
203                 dvert->dw = MEM_callocN(sizeof(*dvert->dw) * totweight,
204                                                                 "layerInterp_mdeformvert dvert->dw");
205                 dvert->totweight = totweight;
206
207                 for(i = 0, node = dest_dw; node; node = node->next, ++i)
208                         dvert->dw[i] = *((MDeformWeight *)node->link);
209         }
210         else
211                 memset(dvert, 0, sizeof(*dvert));
212
213         BLI_linklist_free(dest_dw, linklist_free_simple);
214 }
215
216
217 static void layerInterp_msticky(void **sources, float *weights,
218                                                                 float *UNUSED(sub_weights), int count, void *dest)
219 {
220         float co[2], w;
221         MSticky *mst;
222         int i;
223
224         co[0] = co[1] = 0.0f;
225         for(i = 0; i < count; i++) {
226                 w = weights ? weights[i] : 1.0f;
227                 mst = (MSticky*)sources[i];
228
229                 co[0] += w*mst->co[0];
230                 co[1] += w*mst->co[1];
231         }
232
233         mst = (MSticky*)dest;
234         mst->co[0] = co[0];
235         mst->co[1] = co[1];
236 }
237
238
239 static void layerCopy_tface(const void *source, void *dest, int count)
240 {
241         const MTFace *source_tf = (const MTFace*)source;
242         MTFace *dest_tf = (MTFace*)dest;
243         int i;
244
245         for(i = 0; i < count; ++i)
246                 dest_tf[i] = source_tf[i];
247 }
248
249 static void layerInterp_tface(void **sources, float *weights,
250                                                           float *sub_weights, int count, void *dest)
251 {
252         MTFace *tf = dest;
253         int i, j, k;
254         float uv[4][2];
255         float *sub_weight;
256
257         if(count <= 0) return;
258
259         memset(uv, 0, sizeof(uv));
260
261         sub_weight = sub_weights;
262         for(i = 0; i < count; ++i) {
263                 float weight = weights ? weights[i] : 1;
264                 MTFace *src = sources[i];
265
266                 for(j = 0; j < 4; ++j) {
267                         if(sub_weights) {
268                                 for(k = 0; k < 4; ++k, ++sub_weight) {
269                                         float w = (*sub_weight) * weight;
270                                         float *tmp_uv = src->uv[k];
271
272                                         uv[j][0] += tmp_uv[0] * w;
273                                         uv[j][1] += tmp_uv[1] * w;
274                                 }
275                         } else {
276                                 uv[j][0] += src->uv[j][0] * weight;
277                                 uv[j][1] += src->uv[j][1] * weight;
278                         }
279                 }
280         }
281
282         *tf = *(MTFace *)sources[0];
283         for(j = 0; j < 4; ++j) {
284                 tf->uv[j][0] = uv[j][0];
285                 tf->uv[j][1] = uv[j][1];
286         }
287 }
288
289 static void layerSwap_tface(void *data, const int *corner_indices)
290 {
291         MTFace *tf = data;
292         float uv[4][2];
293         static const short pin_flags[4] =
294                 { TF_PIN1, TF_PIN2, TF_PIN3, TF_PIN4 };
295         static const char sel_flags[4] =
296                 { TF_SEL1, TF_SEL2, TF_SEL3, TF_SEL4 };
297         short unwrap = tf->unwrap & ~(TF_PIN1 | TF_PIN2 | TF_PIN3 | TF_PIN4);
298         char flag = tf->flag & ~(TF_SEL1 | TF_SEL2 | TF_SEL3 | TF_SEL4);
299         int j;
300
301         for(j = 0; j < 4; ++j) {
302                 int source_index = corner_indices[j];
303
304                 uv[j][0] = tf->uv[source_index][0];
305                 uv[j][1] = tf->uv[source_index][1];
306
307                 // swap pinning flags around
308                 if(tf->unwrap & pin_flags[source_index]) {
309                         unwrap |= pin_flags[j];
310                 }
311
312                 // swap selection flags around
313                 if(tf->flag & sel_flags[source_index]) {
314                         flag |= sel_flags[j];
315                 }
316         }
317
318         memcpy(tf->uv, uv, sizeof(tf->uv));
319         tf->unwrap = unwrap;
320         tf->flag = flag;
321 }
322
323 static void layerDefault_tface(void *data, int count)
324 {
325         static MTFace default_tf = {{{0, 0}, {1, 0}, {1, 1}, {0, 1}}, NULL,
326                                                            0, 0, TF_DYNAMIC|TF_CONVERTED, 0, 0};
327         MTFace *tf = (MTFace*)data;
328         int i;
329
330         for(i = 0; i < count; i++)
331                 tf[i] = default_tf;
332 }
333
334 static void layerCopy_origspace_face(const void *source, void *dest, int count)
335 {
336         const OrigSpaceFace *source_tf = (const OrigSpaceFace*)source;
337         OrigSpaceFace *dest_tf = (OrigSpaceFace*)dest;
338         int i;
339
340         for(i = 0; i < count; ++i)
341                 dest_tf[i] = source_tf[i];
342 }
343
344 static void layerInterp_origspace_face(void **sources, float *weights,
345                                                           float *sub_weights, int count, void *dest)
346 {
347         OrigSpaceFace *osf = dest;
348         int i, j, k;
349         float uv[4][2];
350         float *sub_weight;
351
352         if(count <= 0) return;
353
354         memset(uv, 0, sizeof(uv));
355
356         sub_weight = sub_weights;
357         for(i = 0; i < count; ++i) {
358                 float weight = weights ? weights[i] : 1;
359                 OrigSpaceFace *src = sources[i];
360
361                 for(j = 0; j < 4; ++j) {
362                         if(sub_weights) {
363                                 for(k = 0; k < 4; ++k, ++sub_weight) {
364                                         float w = (*sub_weight) * weight;
365                                         float *tmp_uv = src->uv[k];
366
367                                         uv[j][0] += tmp_uv[0] * w;
368                                         uv[j][1] += tmp_uv[1] * w;
369                                 }
370                         } else {
371                                 uv[j][0] += src->uv[j][0] * weight;
372                                 uv[j][1] += src->uv[j][1] * weight;
373                         }
374                 }
375         }
376
377         *osf = *(OrigSpaceFace *)sources[0];
378         for(j = 0; j < 4; ++j) {
379                 osf->uv[j][0] = uv[j][0];
380                 osf->uv[j][1] = uv[j][1];
381         }
382 }
383
384 static void layerSwap_origspace_face(void *data, const int *corner_indices)
385 {
386         OrigSpaceFace *osf = data;
387         float uv[4][2];
388         int j;
389
390         for(j = 0; j < 4; ++j) {
391                 uv[j][0] = osf->uv[corner_indices[j]][0];
392                 uv[j][1] = osf->uv[corner_indices[j]][1];
393         }
394         memcpy(osf->uv, uv, sizeof(osf->uv));
395 }
396
397 static void layerDefault_origspace_face(void *data, int count)
398 {
399         static OrigSpaceFace default_osf = {{{0, 0}, {1, 0}, {1, 1}, {0, 1}}};
400         OrigSpaceFace *osf = (OrigSpaceFace*)data;
401         int i;
402
403         for(i = 0; i < count; i++)
404                 osf[i] = default_osf;
405 }
406
407 static void layerSwap_mdisps(void *data, const int *ci)
408 {
409         MDisps *s = data;
410         float (*d)[3] = NULL;
411         int corners, cornersize, S;
412
413         if(s->disps) {
414                 int nverts= (ci[1] == 3) ? 4 : 3; /* silly way to know vertex count of face */
415                 corners= multires_mdisp_corners(s);
416                 cornersize= s->totdisp/corners;
417
418                 if(corners!=nverts) {
419                         /* happens when face changed vertex count in edit mode
420                            if it happened, just forgot displacement */
421
422                         MEM_freeN(s->disps);
423                         s->totdisp= (s->totdisp/corners)*nverts;
424                         s->disps= MEM_callocN(s->totdisp*sizeof(float)*3, "mdisp swap");
425                         return;
426                 }
427
428                 d= MEM_callocN(sizeof(float) * 3 * s->totdisp, "mdisps swap");
429
430                 for(S = 0; S < corners; S++)
431                         memcpy(d + cornersize*S, s->disps + cornersize*ci[S], cornersize*3*sizeof(float));
432                 
433                 MEM_freeN(s->disps);
434                 s->disps= d;
435         }
436 }
437
438 static void layerInterp_mdisps(void **sources, float *UNUSED(weights),
439                                 float *sub_weights, int count, void *dest)
440 {
441         MDisps *d = dest;
442         MDisps *s = NULL;
443         int st, stl;
444         int i, x, y;
445         int side, S, dst_corners, src_corners;
446         float crn_weight[4][2];
447         float (*sw)[4] = (void*)sub_weights;
448         float (*disps)[3], (*out)[3];
449
450         /* happens when flipping normals of newly created mesh */
451         if(!d->totdisp)
452                 return;
453
454         s = sources[0];
455         dst_corners = multires_mdisp_corners(d);
456         src_corners = multires_mdisp_corners(s);
457
458         if(sub_weights && count == 2 && src_corners == 3) {
459                 src_corners = multires_mdisp_corners(sources[1]);
460
461                 /* special case -- converting two triangles to quad */
462                 if(src_corners == 3 && dst_corners == 4) {
463                         MDisps tris[2];
464                         int vindex[4] = {0};
465
466                         for(i = 0; i < 2; i++)
467                                 for(y = 0; y < 4; y++)
468                                         for(x = 0; x < 4; x++)
469                                                 if(sw[x+i*4][y])
470                                                         vindex[x] = y;
471
472                         for(i = 0; i < 2; i++) {
473                                 float sw_m4[4][4] = {{0}};
474                                 int a = 7 & ~(1 << vindex[i*2] | 1 << vindex[i*2+1]);
475
476                                 sw_m4[0][vindex[i*2+1]] = 1;
477                                 sw_m4[1][vindex[i*2]] = 1;
478
479                                 for(x = 0; x < 3; x++)
480                                         if(a & (1 << x))
481                                                 sw_m4[2][x] = 1;
482
483                                 tris[i] = *((MDisps*)sources[i]);
484                                 tris[i].disps = MEM_dupallocN(tris[i].disps);
485                                 layerInterp_mdisps(&sources[i], NULL, (float*)sw_m4, 1, &tris[i]);
486                         }
487
488                         mdisp_join_tris(d, &tris[0], &tris[1]);
489
490                         for(i = 0; i < 2; i++)
491                                 MEM_freeN(tris[i].disps);
492
493                         return;
494                 }
495         }
496
497         /* For now, some restrictions on the input */
498         if(count != 1 || !sub_weights) {
499                 for(i = 0; i < d->totdisp; ++i)
500                         zero_v3(d->disps[i]);
501
502                 return;
503         }
504
505         /* Initialize the destination */
506         disps = MEM_callocN(3*d->totdisp*sizeof(float), "iterp disps");
507
508         side = sqrt(d->totdisp / dst_corners);
509         st = (side<<1)-1;
510         stl = st - 1;
511
512         sw= (void*)sub_weights;
513         for(i = 0; i < 4; ++i) {
514                 crn_weight[i][0] = 0 * sw[i][0] + stl * sw[i][1] + stl * sw[i][2] + 0 * sw[i][3];
515                 crn_weight[i][1] = 0 * sw[i][0] + 0 * sw[i][1] + stl * sw[i][2] + stl * sw[i][3];
516         }
517
518         multires_mdisp_smooth_bounds(s);
519
520         out = disps;
521         for(S = 0; S < dst_corners; S++) {
522                 float base[2], axis_x[2], axis_y[2];
523
524                 mdisp_apply_weight(S, dst_corners, 0, 0, st, crn_weight, &base[0], &base[1]);
525                 mdisp_apply_weight(S, dst_corners, side-1, 0, st, crn_weight, &axis_x[0], &axis_x[1]);
526                 mdisp_apply_weight(S, dst_corners, 0, side-1, st, crn_weight, &axis_y[0], &axis_y[1]);
527
528                 sub_v2_v2(axis_x, base);
529                 sub_v2_v2(axis_y, base);
530                 normalize_v2(axis_x);
531                 normalize_v2(axis_y);
532
533                 for(y = 0; y < side; ++y) {
534                         for(x = 0; x < side; ++x, ++out) {
535                                 int crn;
536                                 float face_u, face_v, crn_u, crn_v;
537
538                                 mdisp_apply_weight(S, dst_corners, x, y, st, crn_weight, &face_u, &face_v);
539                                 crn = mdisp_rot_face_to_quad_crn(src_corners, st, face_u, face_v, &crn_u, &crn_v);
540
541                                 old_mdisps_bilinear((*out), &s->disps[crn*side*side], side, crn_u, crn_v);
542                                 mdisp_flip_disp(crn, dst_corners, axis_x, axis_y, *out);
543                         }
544                 }
545         }
546
547         MEM_freeN(d->disps);
548         d->disps = disps;
549 }
550
551 static void layerCopy_mdisps(const void *source, void *dest, int count)
552 {
553         int i;
554         const MDisps *s = source;
555         MDisps *d = dest;
556
557         for(i = 0; i < count; ++i) {
558                 if(s[i].disps) {
559                         d[i].disps = MEM_dupallocN(s[i].disps);
560                         d[i].totdisp = s[i].totdisp;
561                 }
562                 else {
563                         d[i].disps = NULL;
564                         d[i].totdisp = 0;
565                 }
566                 
567         }
568 }
569
570 static void layerValidate_mdisps(void *data, int sub_elements)
571 {
572         MDisps *disps = data;
573         if(disps->disps) {
574                 int corners = multires_mdisp_corners(disps);
575
576                 if(corners != sub_elements) {
577                         MEM_freeN(disps->disps);
578                         disps->totdisp = disps->totdisp / corners * sub_elements;
579                         disps->disps = MEM_callocN(3*disps->totdisp*sizeof(float), "layerValidate_mdisps");
580                 }
581         }
582 }
583
584 static void layerFree_mdisps(void *data, int count, int UNUSED(size))
585 {
586         int i;
587         MDisps *d = data;
588
589         for(i = 0; i < count; ++i) {
590                 if(d[i].disps)
591                         MEM_freeN(d[i].disps);
592                 d[i].disps = NULL;
593                 d[i].totdisp = 0;
594         }
595 }
596
597 static int layerRead_mdisps(CDataFile *cdf, void *data, int count)
598 {
599         MDisps *d = data;
600         int i;
601
602         for(i = 0; i < count; ++i) {
603                 if(!d[i].disps)
604                         d[i].disps = MEM_callocN(sizeof(float)*3*d[i].totdisp, "mdisps read");
605
606                 if(!cdf_read_data(cdf, d[i].totdisp*3*sizeof(float), d[i].disps)) {
607                         printf("failed to read multires displacement %d/%d %d\n", i, count, d[i].totdisp);
608                         return 0;
609                 }
610         }
611
612         return 1;
613 }
614
615 static int layerWrite_mdisps(CDataFile *cdf, void *data, int count)
616 {
617         MDisps *d = data;
618         int i;
619
620         for(i = 0; i < count; ++i) {
621                 if(!cdf_write_data(cdf, d[i].totdisp*3*sizeof(float), d[i].disps)) {
622                         printf("failed to write multires displacement %d/%d %d\n", i, count, d[i].totdisp);
623                         return 0;
624                 }
625         }
626
627         return 1;
628 }
629
630 static size_t layerFilesize_mdisps(CDataFile *UNUSED(cdf), void *data, int count)
631 {
632         MDisps *d = data;
633         size_t size = 0;
634         int i;
635
636         for(i = 0; i < count; ++i)
637                 size += d[i].totdisp*3*sizeof(float);
638
639         return size;
640 }
641
642 /* --------- */
643
644 static void layerDefault_mloopcol(void *data, int count)
645 {
646         static MLoopCol default_mloopcol = {255,255,255,255};
647         MLoopCol *mlcol = (MLoopCol*)data;
648         int i;
649         for(i = 0; i < count; i++)
650                 mlcol[i] = default_mloopcol;
651
652 }
653
654 static void layerInterp_mloopcol(void **sources, float *weights,
655                                 float *sub_weights, int count, void *dest)
656 {
657         MLoopCol *mc = dest;
658         int i;
659         float *sub_weight;
660         struct {
661                 float a;
662                 float r;
663                 float g;
664                 float b;
665         } col;
666         col.a = col.r = col.g = col.b = 0;
667
668         sub_weight = sub_weights;
669         for(i = 0; i < count; ++i){
670                 float weight = weights ? weights[i] : 1;
671                 MLoopCol *src = sources[i];
672                 if(sub_weights){
673                         col.a += src->a * (*sub_weight) * weight;
674                         col.r += src->r * (*sub_weight) * weight;
675                         col.g += src->g * (*sub_weight) * weight;
676                         col.b += src->b * (*sub_weight) * weight;
677                         sub_weight++;           
678                 } else {
679                         col.a += src->a * weight;
680                         col.r += src->r * weight;
681                         col.g += src->g * weight;
682                         col.b += src->b * weight;
683                 }
684         }
685         
686         /* Subdivide smooth or fractal can cause problems without clamping
687          * although weights should also not cause this situation */
688         CLAMP(col.a, 0.0f, 255.0f);
689         CLAMP(col.r, 0.0f, 255.0f);
690         CLAMP(col.g, 0.0f, 255.0f);
691         CLAMP(col.b, 0.0f, 255.0f);
692         
693         mc->a = (int)col.a;
694         mc->r = (int)col.r;
695         mc->g = (int)col.g;
696         mc->b = (int)col.b;
697 }
698 static void layerInterp_mloopuv(void **sources, float *weights,
699                                 float *sub_weights, int count, void *dest)
700 {
701         MLoopUV *mluv = dest;
702         int i;
703         float *sub_weight;
704         struct {
705                 float u;
706                 float v;
707         }uv;
708         uv.u = uv.v = 0.0;
709
710         sub_weight = sub_weights;
711         for(i = 0; i < count; ++i){
712                 float weight = weights ? weights[i] : 1;
713                 MLoopUV *src = sources[i];
714                 if(sub_weights){
715                         uv.u += src->uv[0] * (*sub_weight) * weight;
716                         uv.v += src->uv[1] * (*sub_weight) * weight;
717                         sub_weight++;           
718                 } else {
719                         uv.u += src->uv[0] * weight;
720                         uv.v += src->uv[1] * weight;
721                 }
722         }
723         mluv->uv[0] = uv.u;
724         mluv->uv[1] = uv.v;
725 }
726
727 static void layerInterp_mcol(void **sources, float *weights,
728                                                          float *sub_weights, int count, void *dest)
729 {
730         MCol *mc = dest;
731         int i, j, k;
732         struct {
733                 float a;
734                 float r;
735                 float g;
736                 float b;
737         } col[4];
738         float *sub_weight;
739
740         if(count <= 0) return;
741
742         memset(col, 0, sizeof(col));
743         
744         sub_weight = sub_weights;
745         for(i = 0; i < count; ++i) {
746                 float weight = weights ? weights[i] : 1;
747
748                 for(j = 0; j < 4; ++j) {
749                         if(sub_weights) {
750                                 MCol *src = sources[i];
751                                 for(k = 0; k < 4; ++k, ++sub_weight, ++src) {
752                                         col[j].a += src->a * (*sub_weight) * weight;
753                                         col[j].r += src->r * (*sub_weight) * weight;
754                                         col[j].g += src->g * (*sub_weight) * weight;
755                                         col[j].b += src->b * (*sub_weight) * weight;
756                                 }
757                         } else {
758                                 MCol *src = sources[i];
759                                 col[j].a += src[j].a * weight;
760                                 col[j].r += src[j].r * weight;
761                                 col[j].g += src[j].g * weight;
762                                 col[j].b += src[j].b * weight;
763                         }
764                 }
765         }
766
767         for(j = 0; j < 4; ++j) {
768                 
769                 /* Subdivide smooth or fractal can cause problems without clamping
770                  * although weights should also not cause this situation */
771                 CLAMP(col[j].a, 0.0f, 255.0f);
772                 CLAMP(col[j].r, 0.0f, 255.0f);
773                 CLAMP(col[j].g, 0.0f, 255.0f);
774                 CLAMP(col[j].b, 0.0f, 255.0f);
775                 
776                 mc[j].a = (int)col[j].a;
777                 mc[j].r = (int)col[j].r;
778                 mc[j].g = (int)col[j].g;
779                 mc[j].b = (int)col[j].b;
780         }
781 }
782
783 static void layerSwap_mcol(void *data, const int *corner_indices)
784 {
785         MCol *mcol = data;
786         MCol col[4];
787         int j;
788
789         for(j = 0; j < 4; ++j)
790                 col[j] = mcol[corner_indices[j]];
791
792         memcpy(mcol, col, sizeof(col));
793 }
794
795 static void layerDefault_mcol(void *data, int count)
796 {
797         static MCol default_mcol = {255, 255, 255, 255};
798         MCol *mcol = (MCol*)data;
799         int i;
800
801         for(i = 0; i < 4*count; i++)
802                 mcol[i] = default_mcol;
803 }
804
805
806
807 static const LayerTypeInfo LAYERTYPEINFO[CD_NUMTYPES] = {
808         /* 0: CD_MVERT */
809         {sizeof(MVert), "MVert", 1, NULL, NULL, NULL, NULL, NULL, NULL},
810         /* 1: CD_MSTICKY */
811         {sizeof(MSticky), "MSticky", 1, NULL, NULL, NULL, layerInterp_msticky, NULL,
812          NULL},
813         /* 2: CD_MDEFORMVERT */
814         {sizeof(MDeformVert), "MDeformVert", 1, NULL, layerCopy_mdeformvert,
815          layerFree_mdeformvert, layerInterp_mdeformvert, NULL, NULL},
816         /* 3: CD_MEDGE */
817         {sizeof(MEdge), "MEdge", 1, NULL, NULL, NULL, NULL, NULL, NULL},
818         /* 4: CD_MFACE */
819         {sizeof(MFace), "MFace", 1, NULL, NULL, NULL, NULL, NULL, NULL},
820         /* 5: CD_MTFACE */
821         {sizeof(MTFace), "MTFace", 1, "UVTex", layerCopy_tface, NULL,
822          layerInterp_tface, layerSwap_tface, layerDefault_tface},
823         /* 6: CD_MCOL */
824         /* 4 MCol structs per face */
825         {sizeof(MCol)*4, "MCol", 4, "Col", NULL, NULL, layerInterp_mcol,
826          layerSwap_mcol, layerDefault_mcol},
827         /* 7: CD_ORIGINDEX */
828         {sizeof(int), "", 0, NULL, NULL, NULL, NULL, NULL, NULL},
829         /* 8: CD_NORMAL */
830         /* 3 floats per normal vector */
831         {sizeof(float)*3, "", 0, NULL, NULL, NULL, NULL, NULL, NULL},
832         /* 9: CD_FLAGS */
833         {sizeof(int), "", 0, NULL, NULL, NULL, NULL, NULL, NULL},
834         /* 10: CD_PROP_FLT */
835         {sizeof(MFloatProperty), "MFloatProperty",1,"Float",NULL,NULL,NULL,NULL},
836         /* 11: CD_PROP_INT */
837         {sizeof(MIntProperty), "MIntProperty",1,"Int",NULL,NULL,NULL,NULL},
838         /* 12: CD_PROP_STR */
839         {sizeof(MStringProperty), "MStringProperty",1,"String",NULL,NULL,NULL,NULL},
840         /* 13: CD_ORIGSPACE */
841         {sizeof(OrigSpaceFace), "OrigSpaceFace", 1, "UVTex", layerCopy_origspace_face, NULL,
842          layerInterp_origspace_face, layerSwap_origspace_face, layerDefault_origspace_face},
843         /* 14: CD_ORCO */
844         {sizeof(float)*3, "", 0, NULL, NULL, NULL, NULL, NULL, NULL},
845         /* 15: CD_MTEXPOLY */
846         {sizeof(MTexPoly), "MTexPoly", 1, "Face Texture", NULL, NULL, NULL, NULL, NULL},
847         /* 16: CD_MLOOPUV */
848         {sizeof(MLoopUV), "MLoopUV", 1, "UV coord", NULL, NULL, layerInterp_mloopuv, NULL, NULL},
849         /* 17: CD_MLOOPCOL */
850         {sizeof(MLoopCol), "MLoopCol", 1, "Col", NULL, NULL, layerInterp_mloopcol, NULL, layerDefault_mloopcol},
851         /* 18: CD_TANGENT */
852         {sizeof(float)*4*4, "", 0, NULL, NULL, NULL, NULL, NULL, NULL},
853         /* 19: CD_MDISPS */
854         {sizeof(MDisps), "MDisps", 1, NULL, layerCopy_mdisps,
855          layerFree_mdisps, layerInterp_mdisps, layerSwap_mdisps, NULL, layerRead_mdisps, layerWrite_mdisps,
856          layerFilesize_mdisps, layerValidate_mdisps},
857         /* 20: CD_WEIGHT_MCOL */
858         {sizeof(MCol)*4, "MCol", 4, "WeightCol", NULL, NULL, layerInterp_mcol,
859          layerSwap_mcol, layerDefault_mcol},
860         /* 21: CD_ID_MCOL */
861         {sizeof(MCol)*4, "MCol", 4, "IDCol", NULL, NULL, layerInterp_mcol,
862          layerSwap_mcol, layerDefault_mcol},
863         /* 22: CD_TEXTURE_MCOL */
864         {sizeof(MCol)*4, "MCol", 4, "TexturedCol", NULL, NULL, layerInterp_mcol,
865          layerSwap_mcol, layerDefault_mcol},
866         /* 23: CD_CLOTH_ORCO */
867         {sizeof(float)*3, "", 0, NULL, NULL, NULL, NULL, NULL, NULL},
868         /* 24: CD_RECAST */
869         {sizeof(MRecast), "MRecast", 1,"Recast",NULL,NULL,NULL,NULL}
870 };
871
872 static const char *LAYERTYPENAMES[CD_NUMTYPES] = {
873         /*   0-4 */ "CDMVert", "CDMSticky", "CDMDeformVert", "CDMEdge", "CDMFace",
874         /*   5-9 */ "CDMTFace", "CDMCol", "CDOrigIndex", "CDNormal", "CDFlags",
875         /* 10-14 */ "CDMFloatProperty", "CDMIntProperty","CDMStringProperty", "CDOrigSpace", "CDOrco",
876         /* 15-19 */ "CDMTexPoly", "CDMLoopUV", "CDMloopCol", "CDTangent", "CDMDisps",
877         /* 20-24 */"CDWeightMCol", "CDIDMCol", "CDTextureMCol", "CDClothOrco", "CDMRecast"
878 };
879
880 const CustomDataMask CD_MASK_BAREMESH =
881         CD_MASK_MVERT | CD_MASK_MEDGE | CD_MASK_MFACE;
882 const CustomDataMask CD_MASK_MESH =
883         CD_MASK_MVERT | CD_MASK_MEDGE | CD_MASK_MFACE |
884         CD_MASK_MSTICKY | CD_MASK_MDEFORMVERT | CD_MASK_MTFACE | CD_MASK_MCOL |
885         CD_MASK_PROP_FLT | CD_MASK_PROP_INT | CD_MASK_PROP_STR | CD_MASK_MDISPS | CD_MASK_RECAST;
886 const CustomDataMask CD_MASK_EDITMESH =
887         CD_MASK_MSTICKY | CD_MASK_MDEFORMVERT | CD_MASK_MTFACE |
888         CD_MASK_MCOL|CD_MASK_PROP_FLT | CD_MASK_PROP_INT | CD_MASK_PROP_STR | CD_MASK_MDISPS | CD_MASK_RECAST;
889 const CustomDataMask CD_MASK_DERIVEDMESH =
890         CD_MASK_MSTICKY | CD_MASK_MDEFORMVERT | CD_MASK_MTFACE |
891         CD_MASK_MCOL | CD_MASK_ORIGINDEX | CD_MASK_PROP_FLT | CD_MASK_PROP_INT | CD_MASK_CLOTH_ORCO |
892         CD_MASK_PROP_STR | CD_MASK_ORIGSPACE | CD_MASK_ORCO | CD_MASK_TANGENT | CD_MASK_WEIGHT_MCOL | CD_MASK_RECAST;
893 const CustomDataMask CD_MASK_BMESH = 
894         CD_MASK_MSTICKY | CD_MASK_MDEFORMVERT | CD_MASK_PROP_FLT | CD_MASK_PROP_INT | CD_MASK_PROP_STR;
895 const CustomDataMask CD_MASK_FACECORNERS =
896         CD_MASK_MTFACE | CD_MASK_MCOL | CD_MASK_MTEXPOLY | CD_MASK_MLOOPUV |
897         CD_MASK_MLOOPCOL;
898
899
900 static const LayerTypeInfo *layerType_getInfo(int type)
901 {
902         if(type < 0 || type >= CD_NUMTYPES) return NULL;
903
904         return &LAYERTYPEINFO[type];
905 }
906
907 static const char *layerType_getName(int type)
908 {
909         if(type < 0 || type >= CD_NUMTYPES) return NULL;
910
911         return LAYERTYPENAMES[type];
912 }
913
914 /********************* CustomData functions *********************/
915 static void customData_update_offsets(CustomData *data);
916
917 static CustomDataLayer *customData_add_layer__internal(CustomData *data,
918         int type, int alloctype, void *layerdata, int totelem, const char *name);
919
920 void CustomData_merge(const struct CustomData *source, struct CustomData *dest,
921                                           CustomDataMask mask, int alloctype, int totelem)
922 {
923         /*const LayerTypeInfo *typeInfo;*/
924         CustomDataLayer *layer, *newlayer;
925         int i, type, number = 0, lasttype = -1, lastactive = 0, lastrender = 0, lastclone = 0, lastmask = 0, lastflag = 0;
926
927         for(i = 0; i < source->totlayer; ++i) {
928                 layer = &source->layers[i];
929                 /*typeInfo = layerType_getInfo(layer->type);*/ /*UNUSED*/
930
931                 type = layer->type;
932
933                 if (type != lasttype) {
934                         number = 0;
935                         lastactive = layer->active;
936                         lastrender = layer->active_rnd;
937                         lastclone = layer->active_clone;
938                         lastmask = layer->active_mask;
939                         lasttype = type;
940                         lastflag = layer->flag;
941                 }
942                 else
943                         number++;
944
945                 if(lastflag & CD_FLAG_NOCOPY) continue;
946                 else if(!((int)mask & (int)(1 << (int)type))) continue;
947                 else if(number < CustomData_number_of_layers(dest, type)) continue;
948
949                 if((alloctype == CD_ASSIGN) && (lastflag & CD_FLAG_NOFREE))
950                         newlayer = customData_add_layer__internal(dest, type, CD_REFERENCE,
951                                 layer->data, totelem, layer->name);
952                 else
953                         newlayer = customData_add_layer__internal(dest, type, alloctype,
954                                 layer->data, totelem, layer->name);
955                 
956                 if(newlayer) {
957                         newlayer->active = lastactive;
958                         newlayer->active_rnd = lastrender;
959                         newlayer->active_clone = lastclone;
960                         newlayer->active_mask = lastmask;
961                         newlayer->flag |= lastflag & (CD_FLAG_EXTERNAL|CD_FLAG_IN_MEMORY);
962                 }
963         }
964 }
965
966 void CustomData_copy(const struct CustomData *source, struct CustomData *dest,
967                                          CustomDataMask mask, int alloctype, int totelem)
968 {
969         memset(dest, 0, sizeof(*dest));
970
971         if(source->external)
972                 dest->external= MEM_dupallocN(source->external);
973
974         CustomData_merge(source, dest, mask, alloctype, totelem);
975 }
976
977 static void customData_free_layer__internal(CustomDataLayer *layer, int totelem)
978 {
979         const LayerTypeInfo *typeInfo;
980
981         if(!(layer->flag & CD_FLAG_NOFREE) && layer->data) {
982                 typeInfo = layerType_getInfo(layer->type);
983
984                 if(typeInfo->free)
985                         typeInfo->free(layer->data, totelem, typeInfo->size);
986
987                 if(layer->data)
988                         MEM_freeN(layer->data);
989         }
990 }
991
992 static void CustomData_external_free(CustomData *data)
993 {
994         if(data->external) {
995                 MEM_freeN(data->external);
996                 data->external= NULL;
997         }
998 }
999
1000 void CustomData_free(CustomData *data, int totelem)
1001 {
1002         int i;
1003
1004         for(i = 0; i < data->totlayer; ++i)
1005                 customData_free_layer__internal(&data->layers[i], totelem);
1006
1007         if(data->layers)
1008                 MEM_freeN(data->layers);
1009         
1010         CustomData_external_free(data);
1011         
1012         memset(data, 0, sizeof(*data));
1013 }
1014
1015 static void customData_update_offsets(CustomData *data)
1016 {
1017         const LayerTypeInfo *typeInfo;
1018         int i, offset = 0;
1019
1020         for(i = 0; i < data->totlayer; ++i) {
1021                 typeInfo = layerType_getInfo(data->layers[i].type);
1022
1023                 data->layers[i].offset = offset;
1024                 offset += typeInfo->size;
1025         }
1026
1027         data->totsize = offset;
1028 }
1029
1030 int CustomData_get_layer_index(const CustomData *data, int type)
1031 {
1032         int i; 
1033
1034         for(i=0; i < data->totlayer; ++i)
1035                 if(data->layers[i].type == type)
1036                         return i;
1037
1038         return -1;
1039 }
1040
1041 int CustomData_get_named_layer_index(const CustomData *data, int type, const char *name)
1042 {
1043         int i;
1044
1045         for(i=0; i < data->totlayer; ++i)
1046                 if(data->layers[i].type == type && strcmp(data->layers[i].name, name)==0)
1047                         return i;
1048
1049         return -1;
1050 }
1051
1052 int CustomData_get_active_layer_index(const CustomData *data, int type)
1053 {
1054         int i;
1055
1056         for(i=0; i < data->totlayer; ++i)
1057                 if(data->layers[i].type == type)
1058                         return i + data->layers[i].active;
1059
1060         return -1;
1061 }
1062
1063 int CustomData_get_render_layer_index(const CustomData *data, int type)
1064 {
1065         int i;
1066
1067         for(i=0; i < data->totlayer; ++i)
1068                 if(data->layers[i].type == type)
1069                         return i + data->layers[i].active_rnd;
1070
1071         return -1;
1072 }
1073
1074 int CustomData_get_clone_layer_index(const CustomData *data, int type)
1075 {
1076         int i;
1077
1078         for(i=0; i < data->totlayer; ++i)
1079                 if(data->layers[i].type == type)
1080                         return i + data->layers[i].active_clone;
1081
1082         return -1;
1083 }
1084
1085 int CustomData_get_stencil_layer_index(const CustomData *data, int type)
1086 {
1087         int i;
1088
1089         for(i=0; i < data->totlayer; ++i)
1090                 if(data->layers[i].type == type)
1091                         return i + data->layers[i].active_mask;
1092
1093         return -1;
1094 }
1095
1096 int CustomData_get_active_layer(const CustomData *data, int type)
1097 {
1098         int i;
1099
1100         for(i=0; i < data->totlayer; ++i)
1101                 if(data->layers[i].type == type)
1102                         return data->layers[i].active;
1103
1104         return -1;
1105 }
1106
1107 int CustomData_get_render_layer(const CustomData *data, int type)
1108 {
1109         int i;
1110
1111         for(i=0; i < data->totlayer; ++i)
1112                 if(data->layers[i].type == type)
1113                         return data->layers[i].active_rnd;
1114
1115         return -1;
1116 }
1117
1118 int CustomData_get_clone_layer(const CustomData *data, int type)
1119 {
1120         int i;
1121
1122         for(i=0; i < data->totlayer; ++i)
1123                 if(data->layers[i].type == type)
1124                         return data->layers[i].active_clone;
1125
1126         return -1;
1127 }
1128
1129 int CustomData_get_stencil_layer(const CustomData *data, int type)
1130 {
1131         int i;
1132
1133         for(i=0; i < data->totlayer; ++i)
1134                 if(data->layers[i].type == type)
1135                         return data->layers[i].active_mask;
1136
1137         return -1;
1138 }
1139
1140 void CustomData_set_layer_active(CustomData *data, int type, int n)
1141 {
1142         int i;
1143
1144         for(i=0; i < data->totlayer; ++i)
1145                 if(data->layers[i].type == type)
1146                         data->layers[i].active = n;
1147 }
1148
1149 void CustomData_set_layer_render(CustomData *data, int type, int n)
1150 {
1151         int i;
1152
1153         for(i=0; i < data->totlayer; ++i)
1154                 if(data->layers[i].type == type)
1155                         data->layers[i].active_rnd = n;
1156 }
1157
1158 void CustomData_set_layer_clone(CustomData *data, int type, int n)
1159 {
1160         int i;
1161
1162         for(i=0; i < data->totlayer; ++i)
1163                 if(data->layers[i].type == type)
1164                         data->layers[i].active_clone = n;
1165 }
1166
1167 void CustomData_set_layer_stencil(CustomData *data, int type, int n)
1168 {
1169         int i;
1170
1171         for(i=0; i < data->totlayer; ++i)
1172                 if(data->layers[i].type == type)
1173                         data->layers[i].active_mask = n;
1174 }
1175
1176 /* for using with an index from CustomData_get_active_layer_index and CustomData_get_render_layer_index */
1177 void CustomData_set_layer_active_index(CustomData *data, int type, int n)
1178 {
1179         int i;
1180
1181         for(i=0; i < data->totlayer; ++i)
1182                 if(data->layers[i].type == type)
1183                         data->layers[i].active = n-i;
1184 }
1185
1186 void CustomData_set_layer_render_index(CustomData *data, int type, int n)
1187 {
1188         int i;
1189
1190         for(i=0; i < data->totlayer; ++i)
1191                 if(data->layers[i].type == type)
1192                         data->layers[i].active_rnd = n-i;
1193 }
1194
1195 void CustomData_set_layer_clone_index(CustomData *data, int type, int n)
1196 {
1197         int i;
1198
1199         for(i=0; i < data->totlayer; ++i)
1200                 if(data->layers[i].type == type)
1201                         data->layers[i].active_clone = n-i;
1202 }
1203
1204 void CustomData_set_layer_stencil_index(CustomData *data, int type, int n)
1205 {
1206         int i;
1207
1208         for(i=0; i < data->totlayer; ++i)
1209                 if(data->layers[i].type == type)
1210                         data->layers[i].active_mask = n-i;
1211 }
1212
1213 void CustomData_set_layer_flag(struct CustomData *data, int type, int flag)
1214 {
1215         int i;
1216
1217         for(i=0; i < data->totlayer; ++i)
1218                 if(data->layers[i].type == type)
1219                         data->layers[i].flag |= flag;
1220 }
1221
1222 static int customData_resize(CustomData *data, int amount)
1223 {
1224         CustomDataLayer *tmp = MEM_callocN(sizeof(*tmp)*(data->maxlayer + amount),
1225                                                                            "CustomData->layers");
1226         if(!tmp) return 0;
1227
1228         data->maxlayer += amount;
1229         if (data->layers) {
1230                 memcpy(tmp, data->layers, sizeof(*tmp) * data->totlayer);
1231                 MEM_freeN(data->layers);
1232         }
1233         data->layers = tmp;
1234
1235         return 1;
1236 }
1237
1238 static CustomDataLayer *customData_add_layer__internal(CustomData *data,
1239         int type, int alloctype, void *layerdata, int totelem, const char *name)
1240 {
1241         const LayerTypeInfo *typeInfo= layerType_getInfo(type);
1242         int size = typeInfo->size * totelem, flag = 0, index = data->totlayer;
1243         void *newlayerdata;
1244
1245         if (!typeInfo->defaultname && CustomData_has_layer(data, type))
1246                 return &data->layers[CustomData_get_layer_index(data, type)];
1247
1248         if((alloctype == CD_ASSIGN) || (alloctype == CD_REFERENCE)) {
1249                 newlayerdata = layerdata;
1250         }
1251         else {
1252                 newlayerdata = MEM_callocN(size, layerType_getName(type));
1253                 if(!newlayerdata)
1254                         return NULL;
1255         }
1256
1257         if (alloctype == CD_DUPLICATE) {
1258                 if(typeInfo->copy)
1259                         typeInfo->copy(layerdata, newlayerdata, totelem);
1260                 else
1261                         memcpy(newlayerdata, layerdata, size);
1262         }
1263         else if (alloctype == CD_DEFAULT) {
1264                 if(typeInfo->set_default)
1265                         typeInfo->set_default((char*)newlayerdata, totelem);
1266         }
1267         else if (alloctype == CD_REFERENCE)
1268                 flag |= CD_FLAG_NOFREE;
1269
1270         if(index >= data->maxlayer) {
1271                 if(!customData_resize(data, CUSTOMDATA_GROW)) {
1272                         if(newlayerdata != layerdata)
1273                                 MEM_freeN(newlayerdata);
1274                         return NULL;
1275                 }
1276         }
1277         
1278         data->totlayer++;
1279
1280         /* keep layers ordered by type */
1281         for( ; index > 0 && data->layers[index - 1].type > type; --index)
1282                 data->layers[index] = data->layers[index - 1];
1283
1284         data->layers[index].type = type;
1285         data->layers[index].flag = flag;
1286         data->layers[index].data = newlayerdata;
1287         if(name || (name=typeInfo->defaultname)) {
1288                 BLI_strncpy(data->layers[index].name, name, 32);
1289                 CustomData_set_layer_unique_name(data, index);
1290         }
1291         else
1292                 data->layers[index].name[0] = '\0';
1293
1294         if(index > 0 && data->layers[index-1].type == type) {
1295                 data->layers[index].active = data->layers[index-1].active;
1296                 data->layers[index].active_rnd = data->layers[index-1].active_rnd;
1297                 data->layers[index].active_clone = data->layers[index-1].active_clone;
1298                 data->layers[index].active_mask = data->layers[index-1].active_mask;
1299         } else {
1300                 data->layers[index].active = 0;
1301                 data->layers[index].active_rnd = 0;
1302                 data->layers[index].active_clone = 0;
1303                 data->layers[index].active_mask = 0;
1304         }
1305         
1306         customData_update_offsets(data);
1307
1308         return &data->layers[index];
1309 }
1310
1311 void *CustomData_add_layer(CustomData *data, int type, int alloctype,
1312                                                    void *layerdata, int totelem)
1313 {
1314         CustomDataLayer *layer;
1315         const LayerTypeInfo *typeInfo= layerType_getInfo(type);
1316         
1317         layer = customData_add_layer__internal(data, type, alloctype, layerdata,
1318                                                                                    totelem, typeInfo->defaultname);
1319
1320         if(layer)
1321                 return layer->data;
1322
1323         return NULL;
1324 }
1325
1326 /*same as above but accepts a name*/
1327 void *CustomData_add_layer_named(CustomData *data, int type, int alloctype,
1328                                                    void *layerdata, int totelem, const char *name)
1329 {
1330         CustomDataLayer *layer;
1331         
1332         layer = customData_add_layer__internal(data, type, alloctype, layerdata,
1333                                                                                    totelem, name);
1334
1335         if(layer)
1336                 return layer->data;
1337
1338         return NULL;
1339 }
1340
1341
1342 int CustomData_free_layer(CustomData *data, int type, int totelem, int index)
1343 {
1344         int i;
1345         
1346         if (index < 0) return 0;
1347
1348         customData_free_layer__internal(&data->layers[index], totelem);
1349
1350         for (i=index+1; i < data->totlayer; ++i)
1351                 data->layers[i-1] = data->layers[i];
1352
1353         data->totlayer--;
1354
1355         /* if layer was last of type in array, set new active layer */
1356         if ((index >= data->totlayer) || (data->layers[index].type != type)) {
1357                 i = CustomData_get_layer_index(data, type);
1358                 
1359                 if (i >= 0)
1360                         for (; i < data->totlayer && data->layers[i].type == type; i++) {
1361                                 data->layers[i].active--;
1362                                 data->layers[i].active_rnd--;
1363                                 data->layers[i].active_clone--;
1364                                 data->layers[i].active_mask--;
1365                         }
1366         }
1367
1368         if (data->totlayer <= data->maxlayer-CUSTOMDATA_GROW)
1369                 customData_resize(data, -CUSTOMDATA_GROW);
1370
1371         customData_update_offsets(data);
1372
1373         return 1;
1374 }
1375
1376 int CustomData_free_layer_active(CustomData *data, int type, int totelem)
1377 {
1378         int index = 0;
1379         index = CustomData_get_active_layer_index(data, type);
1380         if (index < 0) return 0;
1381         return CustomData_free_layer(data, type, totelem, index);
1382 }
1383
1384
1385 void CustomData_free_layers(CustomData *data, int type, int totelem)
1386 {
1387         while (CustomData_has_layer(data, type))
1388                 CustomData_free_layer_active(data, type, totelem);
1389 }
1390
1391 int CustomData_has_layer(const CustomData *data, int type)
1392 {
1393         return (CustomData_get_layer_index(data, type) != -1);
1394 }
1395
1396 int CustomData_number_of_layers(const CustomData *data, int type)
1397 {
1398         int i, number = 0;
1399
1400         for(i = 0; i < data->totlayer; i++)
1401                 if(data->layers[i].type == type)
1402                         number++;
1403         
1404         return number;
1405 }
1406
1407 void *CustomData_duplicate_referenced_layer(struct CustomData *data, int type)
1408 {
1409         CustomDataLayer *layer;
1410         int layer_index;
1411
1412         /* get the layer index of the first layer of type */
1413         layer_index = CustomData_get_active_layer_index(data, type);
1414         if(layer_index < 0) return NULL;
1415
1416         layer = &data->layers[layer_index];
1417
1418         if (layer->flag & CD_FLAG_NOFREE) {
1419                 layer->data = MEM_dupallocN(layer->data);
1420                 layer->flag &= ~CD_FLAG_NOFREE;
1421         }
1422
1423         return layer->data;
1424 }
1425
1426 void *CustomData_duplicate_referenced_layer_named(struct CustomData *data,
1427                                                                                                   int type, const char *name)
1428 {
1429         CustomDataLayer *layer;
1430         int layer_index;
1431
1432         /* get the layer index of the desired layer */
1433         layer_index = CustomData_get_named_layer_index(data, type, name);
1434         if(layer_index < 0) return NULL;
1435
1436         layer = &data->layers[layer_index];
1437
1438         if (layer->flag & CD_FLAG_NOFREE) {
1439                 layer->data = MEM_dupallocN(layer->data);
1440                 layer->flag &= ~CD_FLAG_NOFREE;
1441         }
1442
1443         return layer->data;
1444 }
1445
1446 void CustomData_free_temporary(CustomData *data, int totelem)
1447 {
1448         CustomDataLayer *layer;
1449         int i, j;
1450
1451         for(i = 0, j = 0; i < data->totlayer; ++i) {
1452                 layer = &data->layers[i];
1453
1454                 if (i != j)
1455                         data->layers[j] = data->layers[i];
1456
1457                 if ((layer->flag & CD_FLAG_TEMPORARY) == CD_FLAG_TEMPORARY)
1458                         customData_free_layer__internal(layer, totelem);
1459                 else
1460                         j++;
1461         }
1462
1463         data->totlayer = j;
1464
1465         if(data->totlayer <= data->maxlayer-CUSTOMDATA_GROW)
1466                 customData_resize(data, -CUSTOMDATA_GROW);
1467
1468         customData_update_offsets(data);
1469 }
1470
1471 void CustomData_set_only_copy(const struct CustomData *data,
1472                                                           CustomDataMask mask)
1473 {
1474         int i;
1475
1476         for(i = 0; i < data->totlayer; ++i)
1477                 if(!((int)mask & (int)(1 << (int)data->layers[i].type)))
1478                         data->layers[i].flag |= CD_FLAG_NOCOPY;
1479 }
1480
1481 void CustomData_copy_data(const CustomData *source, CustomData *dest,
1482                                                   int source_index, int dest_index, int count)
1483 {
1484         const LayerTypeInfo *typeInfo;
1485         int src_i, dest_i;
1486         int src_offset;
1487         int dest_offset;
1488
1489         /* copies a layer at a time */
1490         dest_i = 0;
1491         for(src_i = 0; src_i < source->totlayer; ++src_i) {
1492
1493                 /* find the first dest layer with type >= the source type
1494                  * (this should work because layers are ordered by type)
1495                  */
1496                 while(dest_i < dest->totlayer
1497                           && dest->layers[dest_i].type < source->layers[src_i].type)
1498                         ++dest_i;
1499
1500                 /* if there are no more dest layers, we're done */
1501                 if(dest_i >= dest->totlayer) return;
1502
1503                 /* if we found a matching layer, copy the data */
1504                 if(dest->layers[dest_i].type == source->layers[src_i].type) {
1505                         char *src_data = source->layers[src_i].data;
1506                         char *dest_data = dest->layers[dest_i].data;
1507
1508                         typeInfo = layerType_getInfo(source->layers[src_i].type);
1509
1510                         src_offset = source_index * typeInfo->size;
1511                         dest_offset = dest_index * typeInfo->size;
1512
1513                         if(typeInfo->copy)
1514                                 typeInfo->copy(src_data + src_offset,
1515                                                                 dest_data + dest_offset,
1516                                                                 count);
1517                         else
1518                                 memcpy(dest_data + dest_offset,
1519                                            src_data + src_offset,
1520                                            count * typeInfo->size);
1521
1522                         /* if there are multiple source & dest layers of the same type,
1523                          * we don't want to copy all source layers to the same dest, so
1524                          * increment dest_i
1525                          */
1526                         ++dest_i;
1527                 }
1528         }
1529 }
1530
1531 void CustomData_free_elem(CustomData *data, int index, int count)
1532 {
1533         int i;
1534         const LayerTypeInfo *typeInfo;
1535
1536         for(i = 0; i < data->totlayer; ++i) {
1537                 if(!(data->layers[i].flag & CD_FLAG_NOFREE)) {
1538                         typeInfo = layerType_getInfo(data->layers[i].type);
1539
1540                         if(typeInfo->free) {
1541                                 int offset = typeInfo->size * index;
1542
1543                                 typeInfo->free((char *)data->layers[i].data + offset,
1544                                                            count, typeInfo->size);
1545                         }
1546                 }
1547         }
1548 }
1549
1550 #define SOURCE_BUF_SIZE 100
1551
1552 void CustomData_interp(const CustomData *source, CustomData *dest,
1553                                            int *src_indices, float *weights, float *sub_weights,
1554                                            int count, int dest_index)
1555 {
1556         int src_i, dest_i;
1557         int dest_offset;
1558         int j;
1559         void *source_buf[SOURCE_BUF_SIZE];
1560         void **sources = source_buf;
1561
1562         /* slow fallback in case we're interpolating a ridiculous number of
1563          * elements
1564          */
1565         if(count > SOURCE_BUF_SIZE)
1566                 sources = MEM_callocN(sizeof(*sources) * count,
1567                                                           "CustomData_interp sources");
1568
1569         /* interpolates a layer at a time */
1570         dest_i = 0;
1571         for(src_i = 0; src_i < source->totlayer; ++src_i) {
1572                 const LayerTypeInfo *typeInfo= layerType_getInfo(source->layers[src_i].type);
1573                 if(!typeInfo->interp) continue;
1574
1575                 /* find the first dest layer with type >= the source type
1576                  * (this should work because layers are ordered by type)
1577                  */
1578                 while(dest_i < dest->totlayer
1579                           && dest->layers[dest_i].type < source->layers[src_i].type)
1580                         ++dest_i;
1581
1582                 /* if there are no more dest layers, we're done */
1583                 if(dest_i >= dest->totlayer) return;
1584
1585                 /* if we found a matching layer, copy the data */
1586                 if(dest->layers[dest_i].type == source->layers[src_i].type) {
1587                         void *src_data = source->layers[src_i].data;
1588
1589                         for(j = 0; j < count; ++j)
1590                                 sources[j] = (char *)src_data
1591                                                          + typeInfo->size * src_indices[j];
1592
1593                         dest_offset = dest_index * typeInfo->size;
1594
1595                         typeInfo->interp(sources, weights, sub_weights, count,
1596                                                    (char *)dest->layers[dest_i].data + dest_offset);
1597
1598                         /* if there are multiple source & dest layers of the same type,
1599                          * we don't want to copy all source layers to the same dest, so
1600                          * increment dest_i
1601                          */
1602                         ++dest_i;
1603                 }
1604         }
1605
1606         if(count > SOURCE_BUF_SIZE) MEM_freeN(sources);
1607 }
1608
1609 void CustomData_swap(struct CustomData *data, int index, const int *corner_indices)
1610 {
1611         const LayerTypeInfo *typeInfo;
1612         int i;
1613
1614         for(i = 0; i < data->totlayer; ++i) {
1615                 typeInfo = layerType_getInfo(data->layers[i].type);
1616
1617                 if(typeInfo->swap) {
1618                         int offset = typeInfo->size * index;
1619
1620                         typeInfo->swap((char *)data->layers[i].data + offset, corner_indices);
1621                 }
1622         }
1623 }
1624
1625 void *CustomData_get(const CustomData *data, int index, int type)
1626 {
1627         int offset;
1628         int layer_index;
1629         
1630         /* get the layer index of the active layer of type */
1631         layer_index = CustomData_get_active_layer_index(data, type);
1632         if(layer_index < 0) return NULL;
1633
1634         /* get the offset of the desired element */
1635         offset = layerType_getInfo(type)->size * index;
1636
1637         return (char *)data->layers[layer_index].data + offset;
1638 }
1639
1640 void *CustomData_get_layer(const CustomData *data, int type)
1641 {
1642         /* get the layer index of the active layer of type */
1643         int layer_index = CustomData_get_active_layer_index(data, type);
1644         if(layer_index < 0) return NULL;
1645
1646         return data->layers[layer_index].data;
1647 }
1648
1649 void *CustomData_get_layer_n(const CustomData *data, int type, int n)
1650 {
1651         /* get the layer index of the active layer of type */
1652         int layer_index = CustomData_get_layer_index(data, type);
1653         if(layer_index < 0) return NULL;
1654
1655         return data->layers[layer_index+n].data;
1656 }
1657
1658 void *CustomData_get_layer_named(const struct CustomData *data, int type,
1659                                                                  const char *name)
1660 {
1661         int layer_index = CustomData_get_named_layer_index(data, type, name);
1662         if(layer_index < 0) return NULL;
1663
1664         return data->layers[layer_index].data;
1665 }
1666
1667 void *CustomData_set_layer(const CustomData *data, int type, void *ptr)
1668 {
1669         /* get the layer index of the first layer of type */
1670         int layer_index = CustomData_get_active_layer_index(data, type);
1671
1672         if(layer_index < 0) return NULL;
1673
1674         data->layers[layer_index].data = ptr;
1675
1676         return ptr;
1677 }
1678
1679 void *CustomData_set_layer_n(const struct CustomData *data, int type, int n, void *ptr)
1680 {
1681         /* get the layer index of the first layer of type */
1682         int layer_index = CustomData_get_layer_index(data, type);
1683         if(layer_index < 0) return NULL;
1684
1685         data->layers[layer_index+n].data = ptr;
1686
1687         return ptr;
1688 }
1689
1690 void CustomData_set(const CustomData *data, int index, int type, void *source)
1691 {
1692         void *dest = CustomData_get(data, index, type);
1693         const LayerTypeInfo *typeInfo = layerType_getInfo(type);
1694
1695         if(!dest) return;
1696
1697         if(typeInfo->copy)
1698                 typeInfo->copy(source, dest, 1);
1699         else
1700                 memcpy(dest, source, typeInfo->size);
1701 }
1702
1703 /* EditMesh functions */
1704
1705 void CustomData_em_free_block(CustomData *data, void **block)
1706 {
1707         const LayerTypeInfo *typeInfo;
1708         int i;
1709
1710         if(!*block) return;
1711
1712         for(i = 0; i < data->totlayer; ++i) {
1713                 if(!(data->layers[i].flag & CD_FLAG_NOFREE)) {
1714                         typeInfo = layerType_getInfo(data->layers[i].type);
1715
1716                         if(typeInfo->free) {
1717                                 int offset = data->layers[i].offset;
1718                                 typeInfo->free((char*)*block + offset, 1, typeInfo->size);
1719                         }
1720                 }
1721         }
1722
1723         MEM_freeN(*block);
1724         *block = NULL;
1725 }
1726
1727 static void CustomData_em_alloc_block(CustomData *data, void **block)
1728 {
1729         /* TODO: optimize free/alloc */
1730
1731         if (*block)
1732                 CustomData_em_free_block(data, block);
1733
1734         if (data->totsize > 0)
1735                 *block = MEM_callocN(data->totsize, "CustomData EM block");
1736         else
1737                 *block = NULL;
1738 }
1739
1740 void CustomData_em_copy_data(const CustomData *source, CustomData *dest,
1741                                                         void *src_block, void **dest_block)
1742 {
1743         const LayerTypeInfo *typeInfo;
1744         int dest_i, src_i;
1745
1746         if (!*dest_block)
1747                 CustomData_em_alloc_block(dest, dest_block);
1748         
1749         /* copies a layer at a time */
1750         dest_i = 0;
1751         for(src_i = 0; src_i < source->totlayer; ++src_i) {
1752
1753                 /* find the first dest layer with type >= the source type
1754                  * (this should work because layers are ordered by type)
1755                  */
1756                 while(dest_i < dest->totlayer
1757                           && dest->layers[dest_i].type < source->layers[src_i].type)
1758                         ++dest_i;
1759
1760                 /* if there are no more dest layers, we're done */
1761                 if(dest_i >= dest->totlayer) return;
1762
1763                 /* if we found a matching layer, copy the data */
1764                 if(dest->layers[dest_i].type == source->layers[src_i].type &&
1765                         strcmp(dest->layers[dest_i].name, source->layers[src_i].name) == 0) {
1766                         char *src_data = (char*)src_block + source->layers[src_i].offset;
1767                         char *dest_data = (char*)*dest_block + dest->layers[dest_i].offset;
1768
1769                         typeInfo = layerType_getInfo(source->layers[src_i].type);
1770
1771                         if(typeInfo->copy)
1772                                 typeInfo->copy(src_data, dest_data, 1);
1773                         else
1774                                 memcpy(dest_data, src_data, typeInfo->size);
1775
1776                         /* if there are multiple source & dest layers of the same type,
1777                          * we don't want to copy all source layers to the same dest, so
1778                          * increment dest_i
1779                          */
1780                         ++dest_i;
1781                 }
1782         }
1783 }
1784
1785 void CustomData_em_validate_data(CustomData *data, void *block, int sub_elements)
1786 {
1787         int i;
1788         for(i = 0; i < data->totlayer; i++) {
1789                 const LayerTypeInfo *typeInfo = layerType_getInfo(data->layers[i].type);
1790                 char *leayer_data = (char*)block + data->layers[i].offset;
1791
1792                 if(typeInfo->validate)
1793                         typeInfo->validate(leayer_data, sub_elements);
1794         }
1795 }
1796
1797 void *CustomData_em_get(const CustomData *data, void *block, int type)
1798 {
1799         int layer_index;
1800         
1801         /* get the layer index of the first layer of type */
1802         layer_index = CustomData_get_active_layer_index(data, type);
1803         if(layer_index < 0) return NULL;
1804
1805         return (char *)block + data->layers[layer_index].offset;
1806 }
1807
1808 void *CustomData_em_get_n(const CustomData *data, void *block, int type, int n)
1809 {
1810         int layer_index;
1811         
1812         /* get the layer index of the first layer of type */
1813         layer_index = CustomData_get_layer_index(data, type);
1814         if(layer_index < 0) return NULL;
1815
1816         return (char *)block + data->layers[layer_index+n].offset;
1817 }
1818
1819 void CustomData_em_set(CustomData *data, void *block, int type, void *source)
1820 {
1821         void *dest = CustomData_em_get(data, block, type);
1822         const LayerTypeInfo *typeInfo = layerType_getInfo(type);
1823
1824         if(!dest) return;
1825
1826         if(typeInfo->copy)
1827                 typeInfo->copy(source, dest, 1);
1828         else
1829                 memcpy(dest, source, typeInfo->size);
1830 }
1831
1832 void CustomData_em_set_n(CustomData *data, void *block, int type, int n, void *source)
1833 {
1834         void *dest = CustomData_em_get_n(data, block, type, n);
1835         const LayerTypeInfo *typeInfo = layerType_getInfo(type);
1836
1837         if(!dest) return;
1838
1839         if(typeInfo->copy)
1840                 typeInfo->copy(source, dest, 1);
1841         else
1842                 memcpy(dest, source, typeInfo->size);
1843 }
1844
1845 void CustomData_em_interp(CustomData *data, void **src_blocks, float *weights,
1846                                                   float *sub_weights, int count, void *dest_block)
1847 {
1848         int i, j;
1849         void *source_buf[SOURCE_BUF_SIZE];
1850         void **sources = source_buf;
1851
1852         /* slow fallback in case we're interpolating a ridiculous number of
1853          * elements
1854          */
1855         if(count > SOURCE_BUF_SIZE)
1856                 sources = MEM_callocN(sizeof(*sources) * count,
1857                                                           "CustomData_interp sources");
1858
1859         /* interpolates a layer at a time */
1860         for(i = 0; i < data->totlayer; ++i) {
1861                 CustomDataLayer *layer = &data->layers[i];
1862                 const LayerTypeInfo *typeInfo = layerType_getInfo(layer->type);
1863
1864                 if(typeInfo->interp) {
1865                         for(j = 0; j < count; ++j)
1866                                 sources[j] = (char *)src_blocks[j] + layer->offset;
1867
1868                         typeInfo->interp(sources, weights, sub_weights, count,
1869                                                           (char *)dest_block + layer->offset);
1870                 }
1871         }
1872
1873         if(count > SOURCE_BUF_SIZE) MEM_freeN(sources);
1874 }
1875
1876 void CustomData_em_set_default(CustomData *data, void **block)
1877 {
1878         const LayerTypeInfo *typeInfo;
1879         int i;
1880
1881         if (!*block)
1882                 CustomData_em_alloc_block(data, block);
1883
1884         for(i = 0; i < data->totlayer; ++i) {
1885                 int offset = data->layers[i].offset;
1886
1887                 typeInfo = layerType_getInfo(data->layers[i].type);
1888
1889                 if(typeInfo->set_default)
1890                         typeInfo->set_default((char*)*block + offset, 1);
1891         }
1892 }
1893
1894 void CustomData_to_em_block(const CustomData *source, CustomData *dest,
1895                                                         int src_index, void **dest_block)
1896 {
1897         const LayerTypeInfo *typeInfo;
1898         int dest_i, src_i, src_offset;
1899
1900         if (!*dest_block)
1901                 CustomData_em_alloc_block(dest, dest_block);
1902         
1903         /* copies a layer at a time */
1904         dest_i = 0;
1905         for(src_i = 0; src_i < source->totlayer; ++src_i) {
1906
1907                 /* find the first dest layer with type >= the source type
1908                  * (this should work because layers are ordered by type)
1909                  */
1910                 while(dest_i < dest->totlayer
1911                           && dest->layers[dest_i].type < source->layers[src_i].type)
1912                         ++dest_i;
1913
1914                 /* if there are no more dest layers, we're done */
1915                 if(dest_i >= dest->totlayer) return;
1916
1917                 /* if we found a matching layer, copy the data */
1918                 if(dest->layers[dest_i].type == source->layers[src_i].type) {
1919                         int offset = dest->layers[dest_i].offset;
1920                         char *src_data = source->layers[src_i].data;
1921                         char *dest_data = (char*)*dest_block + offset;
1922
1923                         typeInfo = layerType_getInfo(dest->layers[dest_i].type);
1924                         src_offset = src_index * typeInfo->size;
1925
1926                         if(typeInfo->copy)
1927                                 typeInfo->copy(src_data + src_offset, dest_data, 1);
1928                         else
1929                                 memcpy(dest_data, src_data + src_offset, typeInfo->size);
1930
1931                         /* if there are multiple source & dest layers of the same type,
1932                          * we don't want to copy all source layers to the same dest, so
1933                          * increment dest_i
1934                          */
1935                         ++dest_i;
1936                 }
1937         }
1938 }
1939
1940 void CustomData_from_em_block(const CustomData *source, CustomData *dest,
1941                                                           void *src_block, int dest_index)
1942 {
1943         const LayerTypeInfo *typeInfo;
1944         int dest_i, src_i, dest_offset;
1945
1946         /* copies a layer at a time */
1947         dest_i = 0;
1948         for(src_i = 0; src_i < source->totlayer; ++src_i) {
1949
1950                 /* find the first dest layer with type >= the source type
1951                  * (this should work because layers are ordered by type)
1952                  */
1953                 while(dest_i < dest->totlayer
1954                           && dest->layers[dest_i].type < source->layers[src_i].type)
1955                         ++dest_i;
1956
1957                 /* if there are no more dest layers, we're done */
1958                 if(dest_i >= dest->totlayer) return;
1959
1960                 /* if we found a matching layer, copy the data */
1961                 if(dest->layers[dest_i].type == source->layers[src_i].type) {
1962                         int offset = source->layers[src_i].offset;
1963                         char *src_data = (char*)src_block + offset;
1964                         char *dest_data = dest->layers[dest_i].data;
1965
1966                         typeInfo = layerType_getInfo(dest->layers[dest_i].type);
1967                         dest_offset = dest_index * typeInfo->size;
1968
1969                         if(typeInfo->copy)
1970                                 typeInfo->copy(src_data, dest_data + dest_offset, 1);
1971                         else
1972                                 memcpy(dest_data + dest_offset, src_data, typeInfo->size);
1973
1974                         /* if there are multiple source & dest layers of the same type,
1975                          * we don't want to copy all source layers to the same dest, so
1976                          * increment dest_i
1977                          */
1978                         ++dest_i;
1979                 }
1980         }
1981
1982 }
1983
1984 /*Bmesh functions*/
1985 /*needed to convert to/from different face reps*/
1986 void CustomData_to_bmeshpoly(CustomData *fdata, CustomData *pdata, CustomData *ldata)
1987 {
1988         int i;
1989         for(i=0; i < fdata->totlayer; i++){
1990                 if(fdata->layers[i].type == CD_MTFACE){
1991                         CustomData_add_layer(pdata, CD_MTEXPOLY, CD_CALLOC, &(fdata->layers[i].name), 0);
1992                         CustomData_add_layer(ldata, CD_MLOOPUV, CD_CALLOC, &(fdata->layers[i].name), 0);
1993                 }
1994                 else if(fdata->layers[i].type == CD_MCOL)
1995                         CustomData_add_layer(ldata, CD_MLOOPCOL, CD_CALLOC, &(fdata->layers[i].name), 0);
1996         }               
1997 }
1998 void CustomData_from_bmeshpoly(CustomData *fdata, CustomData *pdata, CustomData *ldata, int total){
1999         int i;
2000         for(i=0; i < pdata->totlayer; i++){
2001                 if(pdata->layers[i].type == CD_MTEXPOLY)
2002                         CustomData_add_layer(fdata, CD_MTFACE, CD_CALLOC, &(pdata->layers[i].name), total);
2003         }
2004         for(i=0; i < ldata->totlayer; i++){
2005                 if(ldata->layers[i].type == CD_MLOOPCOL)
2006                         CustomData_add_layer(fdata, CD_MCOL, CD_CALLOC, &(ldata->layers[i].name), total);
2007         }
2008 }
2009
2010
2011 void CustomData_bmesh_init_pool(CustomData *data, int allocsize){
2012         if(data->totlayer)data->pool = BLI_mempool_create(data->totsize, allocsize, allocsize, 0);
2013 }
2014
2015 void CustomData_bmesh_free_block(CustomData *data, void **block)
2016 {
2017         const LayerTypeInfo *typeInfo;
2018         int i;
2019
2020         if(!*block) return;
2021         for(i = 0; i < data->totlayer; ++i) {
2022                 if(!(data->layers[i].flag & CD_FLAG_NOFREE)) {
2023                         typeInfo = layerType_getInfo(data->layers[i].type);
2024
2025                         if(typeInfo->free) {
2026                                 int offset = data->layers[i].offset;
2027                                 typeInfo->free((char*)*block + offset, 1, typeInfo->size);
2028                         }
2029                 }
2030         }
2031
2032         BLI_mempool_free(data->pool, *block);
2033         *block = NULL;
2034 }
2035
2036 static void CustomData_bmesh_alloc_block(CustomData *data, void **block)
2037 {
2038
2039         if (*block)
2040                 CustomData_bmesh_free_block(data, block);
2041
2042         if (data->totsize > 0)
2043                 *block = BLI_mempool_calloc(data->pool);
2044         else
2045                 *block = NULL;
2046 }
2047
2048 void CustomData_bmesh_copy_data(const CustomData *source, CustomData *dest,
2049                                                         void *src_block, void **dest_block)
2050 {
2051         const LayerTypeInfo *typeInfo;
2052         int dest_i, src_i;
2053
2054         if (!*dest_block)
2055                 CustomData_bmesh_alloc_block(dest, dest_block);
2056         
2057         /* copies a layer at a time */
2058         dest_i = 0;
2059         for(src_i = 0; src_i < source->totlayer; ++src_i) {
2060
2061                 /* find the first dest layer with type >= the source type
2062                  * (this should work because layers are ordered by type)
2063                  */
2064                 while(dest_i < dest->totlayer
2065                           && dest->layers[dest_i].type < source->layers[src_i].type)
2066                         ++dest_i;
2067
2068                 /* if there are no more dest layers, we're done */
2069                 if(dest_i >= dest->totlayer) return;
2070
2071                 /* if we found a matching layer, copy the data */
2072                 if(dest->layers[dest_i].type == source->layers[src_i].type &&
2073                         strcmp(dest->layers[dest_i].name, source->layers[src_i].name) == 0) {
2074                         char *src_data = (char*)src_block + source->layers[src_i].offset;
2075                         char *dest_data = (char*)*dest_block + dest->layers[dest_i].offset;
2076
2077                         typeInfo = layerType_getInfo(source->layers[src_i].type);
2078
2079                         if(typeInfo->copy)
2080                                 typeInfo->copy(src_data, dest_data, 1);
2081                         else
2082                                 memcpy(dest_data, src_data, typeInfo->size);
2083
2084                         /* if there are multiple source & dest layers of the same type,
2085                          * we don't want to copy all source layers to the same dest, so
2086                          * increment dest_i
2087                          */
2088                         ++dest_i;
2089                 }
2090         }
2091 }
2092
2093 /*Bmesh Custom Data Functions. Should replace editmesh ones with these as well, due to more effecient memory alloc*/
2094 void *CustomData_bmesh_get(const CustomData *data, void *block, int type)
2095 {
2096         int layer_index;
2097         
2098         /* get the layer index of the first layer of type */
2099         layer_index = CustomData_get_active_layer_index(data, type);
2100         if(layer_index < 0) return NULL;
2101
2102         return (char *)block + data->layers[layer_index].offset;
2103 }
2104
2105 void *CustomData_bmesh_get_n(const CustomData *data, void *block, int type, int n)
2106 {
2107         int layer_index;
2108         
2109         /* get the layer index of the first layer of type */
2110         layer_index = CustomData_get_layer_index(data, type);
2111         if(layer_index < 0) return NULL;
2112
2113         return (char *)block + data->layers[layer_index+n].offset;
2114 }
2115
2116 void CustomData_bmesh_set(const CustomData *data, void *block, int type, void *source)
2117 {
2118         void *dest = CustomData_bmesh_get(data, block, type);
2119         const LayerTypeInfo *typeInfo = layerType_getInfo(type);
2120
2121         if(!dest) return;
2122
2123         if(typeInfo->copy)
2124                 typeInfo->copy(source, dest, 1);
2125         else
2126                 memcpy(dest, source, typeInfo->size);
2127 }
2128
2129 void CustomData_bmesh_set_n(CustomData *data, void *block, int type, int n, void *source)
2130 {
2131         void *dest = CustomData_bmesh_get_n(data, block, type, n);
2132         const LayerTypeInfo *typeInfo = layerType_getInfo(type);
2133
2134         if(!dest) return;
2135
2136         if(typeInfo->copy)
2137                 typeInfo->copy(source, dest, 1);
2138         else
2139                 memcpy(dest, source, typeInfo->size);
2140 }
2141
2142 void CustomData_bmesh_interp(CustomData *data, void **src_blocks, float *weights,
2143                                                   float *sub_weights, int count, void *dest_block)
2144 {
2145         int i, j;
2146         void *source_buf[SOURCE_BUF_SIZE];
2147         void **sources = source_buf;
2148
2149         /* slow fallback in case we're interpolating a ridiculous number of
2150          * elements
2151          */
2152         if(count > SOURCE_BUF_SIZE)
2153                 sources = MEM_callocN(sizeof(*sources) * count,
2154                                                           "CustomData_interp sources");
2155
2156         /* interpolates a layer at a time */
2157         for(i = 0; i < data->totlayer; ++i) {
2158                 CustomDataLayer *layer = &data->layers[i];
2159                 const LayerTypeInfo *typeInfo = layerType_getInfo(layer->type);
2160                 if(typeInfo->interp) {
2161                         for(j = 0; j < count; ++j)
2162                                 sources[j] = (char *)src_blocks[j] + layer->offset;
2163
2164                         typeInfo->interp(sources, weights, sub_weights, count,
2165                                                           (char *)dest_block + layer->offset);
2166                 }
2167         }
2168
2169         if(count > SOURCE_BUF_SIZE) MEM_freeN(sources);
2170 }
2171
2172 void CustomData_bmesh_set_default(CustomData *data, void **block)
2173 {
2174         const LayerTypeInfo *typeInfo;
2175         int i;
2176
2177         if (!*block)
2178                 CustomData_bmesh_alloc_block(data, block);
2179
2180         for(i = 0; i < data->totlayer; ++i) {
2181                 int offset = data->layers[i].offset;
2182
2183                 typeInfo = layerType_getInfo(data->layers[i].type);
2184
2185                 if(typeInfo->set_default)
2186                         typeInfo->set_default((char*)*block + offset, 1);
2187         }
2188 }
2189
2190 void CustomData_to_bmesh_block(const CustomData *source, CustomData *dest,
2191                                                         int src_index, void **dest_block)
2192 {
2193         const LayerTypeInfo *typeInfo;
2194         int dest_i, src_i, src_offset;
2195
2196         if (!*dest_block)
2197                 CustomData_bmesh_alloc_block(dest, dest_block);
2198         
2199         /* copies a layer at a time */
2200         dest_i = 0;
2201         for(src_i = 0; src_i < source->totlayer; ++src_i) {
2202
2203                 /* find the first dest layer with type >= the source type
2204                  * (this should work because layers are ordered by type)
2205                  */
2206                 while(dest_i < dest->totlayer
2207                           && dest->layers[dest_i].type < source->layers[src_i].type)
2208                         ++dest_i;
2209
2210                 /* if there are no more dest layers, we're done */
2211                 if(dest_i >= dest->totlayer) return;
2212
2213                 /* if we found a matching layer, copy the data */
2214                 if(dest->layers[dest_i].type == source->layers[src_i].type) {
2215                         int offset = dest->layers[dest_i].offset;
2216                         char *src_data = source->layers[src_i].data;
2217                         char *dest_data = (char*)*dest_block + offset;
2218
2219                         typeInfo = layerType_getInfo(dest->layers[dest_i].type);
2220                         src_offset = src_index * typeInfo->size;
2221
2222                         if(typeInfo->copy)
2223                                 typeInfo->copy(src_data + src_offset, dest_data, 1);
2224                         else
2225                                 memcpy(dest_data, src_data + src_offset, typeInfo->size);
2226
2227                         /* if there are multiple source & dest layers of the same type,
2228                          * we don't want to copy all source layers to the same dest, so
2229                          * increment dest_i
2230                          */
2231                         ++dest_i;
2232                 }
2233         }
2234 }
2235
2236 void CustomData_from_bmesh_block(const CustomData *source, CustomData *dest,
2237                                                           void *src_block, int dest_index)
2238 {
2239         const LayerTypeInfo *typeInfo;
2240         int dest_i, src_i, dest_offset;
2241
2242         /* copies a layer at a time */
2243         dest_i = 0;
2244         for(src_i = 0; src_i < source->totlayer; ++src_i) {
2245
2246                 /* find the first dest layer with type >= the source type
2247                  * (this should work because layers are ordered by type)
2248                  */
2249                 while(dest_i < dest->totlayer
2250                           && dest->layers[dest_i].type < source->layers[src_i].type)
2251                         ++dest_i;
2252
2253                 /* if there are no more dest layers, we're done */
2254                 if(dest_i >= dest->totlayer) return;
2255
2256                 /* if we found a matching layer, copy the data */
2257                 if(dest->layers[dest_i].type == source->layers[src_i].type) {
2258                         int offset = source->layers[src_i].offset;
2259                         char *src_data = (char*)src_block + offset;
2260                         char *dest_data = dest->layers[dest_i].data;
2261
2262                         typeInfo = layerType_getInfo(dest->layers[dest_i].type);
2263                         dest_offset = dest_index * typeInfo->size;
2264
2265                         if(typeInfo->copy)
2266                                 typeInfo->copy(src_data, dest_data + dest_offset, 1);
2267                         else
2268                                 memcpy(dest_data + dest_offset, src_data, typeInfo->size);
2269
2270                         /* if there are multiple source & dest layers of the same type,
2271                          * we don't want to copy all source layers to the same dest, so
2272                          * increment dest_i
2273                          */
2274                         ++dest_i;
2275                 }
2276         }
2277
2278 }
2279
2280 void CustomData_file_write_info(int type, const char **structname, int *structnum)
2281 {
2282         const LayerTypeInfo *typeInfo = layerType_getInfo(type);
2283
2284         *structname = typeInfo->structname;
2285         *structnum = typeInfo->structnum;
2286 }
2287
2288 int CustomData_sizeof(int type)
2289 {
2290         const LayerTypeInfo *typeInfo = layerType_getInfo(type);
2291
2292         return typeInfo->size;
2293 }
2294
2295 const char *CustomData_layertype_name(int type)
2296 {
2297         return layerType_getName(type);
2298 }
2299
2300 static int  CustomData_is_property_layer(int type)
2301 {
2302         if((type == CD_PROP_FLT) || (type == CD_PROP_INT) || (type == CD_PROP_STR))
2303                 return 1;
2304         return 0;
2305 }
2306
2307 static int cd_layer_find_dupe(CustomData *data, const char *name, int type, int index)
2308 {
2309         int i;
2310         /* see if there is a duplicate */
2311         for(i=0; i<data->totlayer; i++) {
2312                 if(i != index) {
2313                         CustomDataLayer *layer= &data->layers[i];
2314                         
2315                         if(CustomData_is_property_layer(type)) {
2316                                 if(CustomData_is_property_layer(layer->type) && strcmp(layer->name, name)==0) {
2317                                         return 1;
2318                                 }
2319                         }
2320                         else{
2321                                 if(i!=index && layer->type==type && strcmp(layer->name, name)==0) {
2322                                         return 1;
2323                                 }
2324                         }
2325                 }
2326         }
2327         
2328         return 0;
2329 }
2330
2331 static int customdata_unique_check(void *arg, const char *name)
2332 {
2333         struct {CustomData *data; int type; int index;} *data_arg= arg;
2334         return cd_layer_find_dupe(data_arg->data, name, data_arg->type, data_arg->index);
2335 }
2336
2337 void CustomData_set_layer_unique_name(CustomData *data, int index)
2338 {       
2339         CustomDataLayer *nlayer= &data->layers[index];
2340         const LayerTypeInfo *typeInfo= layerType_getInfo(nlayer->type);
2341
2342         struct {CustomData *data; int type; int index;} data_arg;
2343         data_arg.data= data;
2344         data_arg.type= nlayer->type;
2345         data_arg.index= index;
2346
2347         if (!typeInfo->defaultname)
2348                 return;
2349         
2350         BLI_uniquename_cb(customdata_unique_check, &data_arg, typeInfo->defaultname, '.', nlayer->name, sizeof(nlayer->name));
2351 }
2352
2353 int CustomData_verify_versions(struct CustomData *data, int index)
2354 {
2355         const LayerTypeInfo *typeInfo;
2356         CustomDataLayer *layer = &data->layers[index];
2357         int i, keeplayer = 1;
2358
2359         if (layer->type >= CD_NUMTYPES) {
2360                 keeplayer = 0; /* unknown layer type from future version */
2361         }
2362         else {
2363                 typeInfo = layerType_getInfo(layer->type);
2364
2365                 if (!typeInfo->defaultname && (index > 0) &&
2366                         data->layers[index-1].type == layer->type)
2367                         keeplayer = 0; /* multiple layers of which we only support one */
2368         }
2369
2370         if (!keeplayer) {
2371                 for (i=index+1; i < data->totlayer; ++i)
2372                         data->layers[i-1] = data->layers[i];
2373                 data->totlayer--;
2374         }
2375
2376         return keeplayer;
2377 }
2378
2379 /****************************** External Files *******************************/
2380
2381 static void customdata_external_filename(char filename[FILE_MAX], ID *id, CustomDataExternal *external)
2382 {
2383         BLI_strncpy(filename, external->filename, FILE_MAX);
2384         BLI_path_abs(filename, ID_BLEND_PATH(G.main, id));
2385 }
2386
2387 void CustomData_external_reload(CustomData *data, ID *UNUSED(id), CustomDataMask mask, int totelem)
2388 {
2389         CustomDataLayer *layer;
2390         const LayerTypeInfo *typeInfo;
2391         int i;
2392
2393         for(i=0; i<data->totlayer; i++) {
2394                 layer = &data->layers[i];
2395                 typeInfo = layerType_getInfo(layer->type);
2396
2397                 if(!(mask & (1<<layer->type)));
2398                 else if((layer->flag & CD_FLAG_EXTERNAL) && (layer->flag & CD_FLAG_IN_MEMORY)) {
2399                         if(typeInfo->free)
2400                                 typeInfo->free(layer->data, totelem, typeInfo->size);
2401                         layer->flag &= ~CD_FLAG_IN_MEMORY;
2402                 }
2403         }
2404 }
2405
2406 void CustomData_external_read(CustomData *data, ID *id, CustomDataMask mask, int totelem)
2407 {
2408         CustomDataExternal *external= data->external;
2409         CustomDataLayer *layer;
2410         CDataFile *cdf;
2411         CDataFileLayer *blay;
2412         char filename[FILE_MAX];
2413         const LayerTypeInfo *typeInfo;
2414         int i, update = 0;
2415
2416         if(!external)
2417                 return;
2418         
2419         for(i=0; i<data->totlayer; i++) {
2420                 layer = &data->layers[i];
2421                 typeInfo = layerType_getInfo(layer->type);
2422
2423                 if(!(mask & (1<<layer->type)));
2424                 else if(layer->flag & CD_FLAG_IN_MEMORY);
2425                 else if((layer->flag & CD_FLAG_EXTERNAL) && typeInfo->read)
2426                         update= 1;
2427         }
2428
2429         if(!update)
2430                 return;
2431
2432         customdata_external_filename(filename, id, external);
2433
2434         cdf= cdf_create(CDF_TYPE_MESH);
2435         if(!cdf_read_open(cdf, filename)) {
2436                 fprintf(stderr, "Failed to read %s layer from %s.\n", layerType_getName(layer->type), filename);
2437                 return;
2438         }
2439
2440         for(i=0; i<data->totlayer; i++) {
2441                 layer = &data->layers[i];
2442                 typeInfo = layerType_getInfo(layer->type);
2443
2444                 if(!(mask & (1<<layer->type)));
2445                 else if(layer->flag & CD_FLAG_IN_MEMORY);
2446                 else if((layer->flag & CD_FLAG_EXTERNAL) && typeInfo->read) {
2447                         blay= cdf_layer_find(cdf, layer->type, layer->name);
2448
2449                         if(blay) {
2450                                 if(cdf_read_layer(cdf, blay)) {
2451                                         if(typeInfo->read(cdf, layer->data, totelem));
2452                                         else break;
2453                                         layer->flag |= CD_FLAG_IN_MEMORY;
2454                                 }
2455                                 else
2456                                         break;
2457                         }
2458                 }
2459         }
2460
2461         cdf_read_close(cdf);
2462         cdf_free(cdf);
2463 }
2464
2465 void CustomData_external_write(CustomData *data, ID *id, CustomDataMask mask, int totelem, int free)
2466 {
2467         CustomDataExternal *external= data->external;
2468         CustomDataLayer *layer;
2469         CDataFile *cdf;
2470         CDataFileLayer *blay;
2471         const LayerTypeInfo *typeInfo;
2472         int i, update = 0;
2473         char filename[FILE_MAX];
2474
2475         if(!external)
2476                 return;
2477
2478         /* test if there is anything to write */
2479         for(i=0; i<data->totlayer; i++) {
2480                 layer = &data->layers[i];
2481                 typeInfo = layerType_getInfo(layer->type);
2482
2483                 if(!(mask & (1<<layer->type)));
2484                 else if((layer->flag & CD_FLAG_EXTERNAL) && typeInfo->write)
2485                         update= 1;
2486         }
2487
2488         if(!update)
2489                 return;
2490
2491         /* make sure data is read before we try to write */
2492         CustomData_external_read(data, id, mask, totelem);
2493         customdata_external_filename(filename, id, external);
2494
2495         cdf= cdf_create(CDF_TYPE_MESH);
2496
2497         for(i=0; i<data->totlayer; i++) {
2498                 layer = &data->layers[i];
2499                 typeInfo = layerType_getInfo(layer->type);
2500
2501                 if((layer->flag & CD_FLAG_EXTERNAL) && typeInfo->filesize) {
2502                         if(layer->flag & CD_FLAG_IN_MEMORY) {
2503                                 cdf_layer_add(cdf, layer->type, layer->name,
2504                                         typeInfo->filesize(cdf, layer->data, totelem));
2505                         }
2506                         else {
2507                                 cdf_free(cdf);
2508                                 return; /* read failed for a layer! */
2509                         }
2510                 }
2511         }
2512
2513         if(!cdf_write_open(cdf, filename)) {
2514                 fprintf(stderr, "Failed to open %s for writing.\n", filename);
2515                 return;
2516         }
2517
2518         for(i=0; i<data->totlayer; i++) {
2519                 layer = &data->layers[i];
2520                 typeInfo = layerType_getInfo(layer->type);
2521
2522                 if((layer->flag & CD_FLAG_EXTERNAL) && typeInfo->write) {
2523                         blay= cdf_layer_find(cdf, layer->type, layer->name);
2524
2525                         if(cdf_write_layer(cdf, blay)) {
2526                                 if(typeInfo->write(cdf, layer->data, totelem));
2527                                 else break;
2528                         }
2529                         else
2530                                 break;
2531                 }
2532         }
2533
2534         if(i != data->totlayer) {
2535                 fprintf(stderr, "Failed to write data to %s.\n", filename);
2536                 cdf_free(cdf);
2537                 return;
2538         }
2539
2540         for(i=0; i<data->totlayer; i++) {
2541                 layer = &data->layers[i];
2542                 typeInfo = layerType_getInfo(layer->type);
2543
2544                 if((layer->flag & CD_FLAG_EXTERNAL) && typeInfo->write) {
2545                         if(free) {
2546                                 if(typeInfo->free)
2547                                         typeInfo->free(layer->data, totelem, typeInfo->size);
2548                                 layer->flag &= ~CD_FLAG_IN_MEMORY;
2549                         }
2550                 }
2551         }
2552
2553         cdf_write_close(cdf);
2554         cdf_free(cdf);
2555 }
2556
2557 void CustomData_external_add(CustomData *data, ID *UNUSED(id), int type, int UNUSED(totelem), const char *filename)
2558 {
2559         CustomDataExternal *external= data->external;
2560         CustomDataLayer *layer;
2561         int layer_index;
2562
2563         layer_index = CustomData_get_active_layer_index(data, type);
2564         if(layer_index < 0) return;
2565
2566         layer = &data->layers[layer_index];
2567
2568         if(layer->flag & CD_FLAG_EXTERNAL)
2569                 return;
2570
2571         if(!external) {
2572                 external= MEM_callocN(sizeof(CustomDataExternal), "CustomDataExternal");
2573                 data->external= external;
2574         }
2575         BLI_strncpy(external->filename, filename, sizeof(external->filename));
2576
2577         layer->flag |= CD_FLAG_EXTERNAL|CD_FLAG_IN_MEMORY;
2578 }
2579
2580 void CustomData_external_remove(CustomData *data, ID *id, int type, int totelem)
2581 {
2582         CustomDataExternal *external= data->external;
2583         CustomDataLayer *layer;
2584         //char filename[FILE_MAX];
2585         int layer_index; // i, remove_file;
2586
2587         layer_index = CustomData_get_active_layer_index(data, type);
2588         if(layer_index < 0) return;
2589
2590         layer = &data->layers[layer_index];
2591
2592         if(!external)
2593                 return;
2594
2595         if(layer->flag & CD_FLAG_EXTERNAL) {
2596                 if(!(layer->flag & CD_FLAG_IN_MEMORY))
2597                         CustomData_external_read(data, id, (1<<layer->type), totelem);
2598
2599                 layer->flag &= ~CD_FLAG_EXTERNAL;
2600
2601 #if 0
2602                 remove_file= 1;
2603                 for(i=0; i<data->totlayer; i++)
2604                         if(data->layers[i].flag & CD_FLAG_EXTERNAL)
2605                                 remove_file= 0;
2606
2607                 if(remove_file) {
2608                         customdata_external_filename(filename, id, external);
2609                         cdf_remove(filename);
2610                         CustomData_external_free(data);
2611                 }
2612 #endif
2613         }
2614 }
2615
2616 int CustomData_external_test(CustomData *data, int type)
2617 {
2618         CustomDataLayer *layer;
2619         int layer_index;
2620
2621         layer_index = CustomData_get_active_layer_index(data, type);
2622         if(layer_index < 0) return 0;
2623
2624         layer = &data->layers[layer_index];
2625         return (layer->flag & CD_FLAG_EXTERNAL);
2626 }
2627
2628 #if 0
2629 void CustomData_external_remove_object(CustomData *data, ID *id)
2630 {
2631         CustomDataExternal *external= data->external;
2632         char filename[FILE_MAX];
2633
2634         if(!external)
2635                 return;
2636
2637         customdata_external_filename(filename, id, external);
2638         cdf_remove(filename);
2639         CustomData_external_free(data);
2640 }
2641 #endif
2642