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