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