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