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