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