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