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