part 1 of cleaning up my little array macro library to be a formal API. also removed...
[blender.git] / source / blender / blenkernel / intern / cdderivedmesh.c
1 /*
2 * $Id$
3 *
4 * ***** BEGIN GPL LICENSE BLOCK *****
5 *
6 * This program is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU General Public License
8 * as published by the Free Software Foundation; either version 2
9 * of the License, or (at your option) any later version.
10 *
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14 * GNU General Public License for more details.
15 *
16 * You should have received a copy of the GNU General Public License
17 * along with this program; if not, write to the Free Software  Foundation,
18 * Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
19 *
20 * The Original Code is Copyright (C) 2006 Blender Foundation.
21 * All rights reserved.
22 *
23 * The Original Code is: all of this file.
24 *
25 * Contributor(s): Ben Batt <benbatt@gmail.com>
26 *
27 * ***** END GPL LICENSE BLOCK *****
28 *
29 * Implementation of CDDerivedMesh.
30 *
31 * BKE_cdderivedmesh.h contains the function prototypes for this file.
32 *
33 */ 
34
35 /* TODO maybe BIF_gl.h should include string.h? */
36 #include <string.h>
37 #include "BIF_gl.h"
38
39 #include "BKE_cdderivedmesh.h"
40 #include "BKE_customdata.h"
41 #include "BKE_DerivedMesh.h"
42 #include "BKE_displist.h"
43 #include "BKE_global.h"
44 #include "BKE_mesh.h"
45 #include "BKE_multires.h"
46 #include "BKE_utildefines.h"
47 #include "BKE_tessmesh.h"
48
49 #include "BLI_editVert.h"
50 #include "BLI_scanfill.h"
51 #include "BLI_arithb.h"
52 #include "BLI_blenlib.h"
53 #include "BLI_edgehash.h"
54 #include "BLI_editVert.h"
55 #include "BLI_ghash.h"
56
57 #include "DNA_mesh_types.h"
58 #include "DNA_meshdata_types.h"
59 #include "DNA_modifier_types.h"
60 #include "DNA_object_fluidsim.h"
61 #include "DNA_object_types.h"
62 #include "DNA_scene_types.h"
63
64 #include "MEM_guardedalloc.h"
65
66 #include "GPU_draw.h"
67 #include "GPU_extensions.h"
68 #include "GPU_material.h"
69
70 #include <string.h>
71 #include <limits.h>
72 #include <math.h>
73
74 typedef struct {
75         DerivedMesh dm;
76
77         /* these point to data in the DerivedMesh custom data layers,
78            they are only here for efficiency and convenience **/
79         MVert *mvert;
80         MEdge *medge;
81         MFace *mface;
82         MLoop *mloop;
83         MPoly *mpoly;
84 } CDDerivedMesh;
85
86 DMFaceIter *cdDM_newFaceIter(DerivedMesh *source);
87
88 /**************** DerivedMesh interface functions ****************/
89 static int cdDM_getNumVerts(DerivedMesh *dm)
90 {
91         return dm->numVertData;
92 }
93
94 static int cdDM_getNumEdges(DerivedMesh *dm)
95 {
96         return dm->numEdgeData;
97 }
98
99 static int cdDM_getNumTessFaces(DerivedMesh *dm)
100 {
101         return dm->numFaceData;
102 }
103
104 static int cdDM_getNumFaces(DerivedMesh *dm)
105 {
106         return dm->numPolyData;
107 }
108
109 static void cdDM_getVert(DerivedMesh *dm, int index, MVert *vert_r)
110 {
111         CDDerivedMesh *cddm = (CDDerivedMesh *)dm;
112         *vert_r = cddm->mvert[index];
113 }
114
115 static void cdDM_getEdge(DerivedMesh *dm, int index, MEdge *edge_r)
116 {
117         CDDerivedMesh *cddm = (CDDerivedMesh *)dm;
118         *edge_r = cddm->medge[index];
119 }
120
121 static void cdDM_getFace(DerivedMesh *dm, int index, MFace *face_r)
122 {
123         CDDerivedMesh *cddm = (CDDerivedMesh *)dm;
124         *face_r = cddm->mface[index];
125 }
126
127 static void cdDM_copyVertArray(DerivedMesh *dm, MVert *vert_r)
128 {
129         CDDerivedMesh *cddm = (CDDerivedMesh *)dm;
130         memcpy(vert_r, cddm->mvert, sizeof(*vert_r) * dm->numVertData);
131 }
132
133 static void cdDM_copyEdgeArray(DerivedMesh *dm, MEdge *edge_r)
134 {
135         CDDerivedMesh *cddm = (CDDerivedMesh *)dm;
136         memcpy(edge_r, cddm->medge, sizeof(*edge_r) * dm->numEdgeData);
137 }
138
139 static void cdDM_copyFaceArray(DerivedMesh *dm, MFace *face_r)
140 {
141         CDDerivedMesh *cddm = (CDDerivedMesh *)dm;
142         memcpy(face_r, cddm->mface, sizeof(*face_r) * dm->numFaceData);
143 }
144
145 static void cdDM_getMinMax(DerivedMesh *dm, float min_r[3], float max_r[3])
146 {
147         CDDerivedMesh *cddm = (CDDerivedMesh*) dm;
148         int i;
149
150         if (dm->numVertData) {
151                 for (i=0; i<dm->numVertData; i++) {
152                         DO_MINMAX(cddm->mvert[i].co, min_r, max_r);
153                 }
154         } else {
155                 min_r[0] = min_r[1] = min_r[2] = max_r[0] = max_r[1] = max_r[2] = 0.0;
156         }
157 }
158
159 static void cdDM_getVertCo(DerivedMesh *dm, int index, float co_r[3])
160 {
161         CDDerivedMesh *cddm = (CDDerivedMesh*) dm;
162
163         VECCOPY(co_r, cddm->mvert[index].co);
164 }
165
166 static void cdDM_getVertCos(DerivedMesh *dm, float (*cos_r)[3])
167 {
168         MVert *mv = CDDM_get_verts(dm);
169         int i;
170
171         for(i = 0; i < dm->numVertData; i++, mv++)
172                 VECCOPY(cos_r[i], mv->co);
173 }
174
175 static void cdDM_getVertNo(DerivedMesh *dm, int index, float no_r[3])
176 {
177         CDDerivedMesh *cddm = (CDDerivedMesh*) dm;
178         short *no = cddm->mvert[index].no;
179
180         no_r[0] = no[0]/32767.f;
181         no_r[1] = no[1]/32767.f;
182         no_r[2] = no[2]/32767.f;
183 }
184
185 static void cdDM_drawVerts(DerivedMesh *dm)
186 {
187         CDDerivedMesh *cddm = (CDDerivedMesh*) dm;
188         MVert *mv = cddm->mvert;
189         int i;
190
191         glBegin(GL_POINTS);
192         for(i = 0; i < dm->numVertData; i++, mv++)
193                 glVertex3fv(mv->co);
194         glEnd();
195 }
196
197 static void cdDM_drawUVEdges(DerivedMesh *dm)
198 {
199         CDDerivedMesh *cddm = (CDDerivedMesh*) dm;
200         MFace *mf = cddm->mface;
201         MTFace *tf = DM_get_tessface_data_layer(dm, CD_MTFACE);
202         int i;
203
204         if(mf) {
205                 glBegin(GL_LINES);
206                 for(i = 0; i < dm->numFaceData; i++, mf++, tf++) {
207                         if(!(mf->flag&ME_HIDE)) {
208                                 glVertex2fv(tf->uv[0]);
209                                 glVertex2fv(tf->uv[1]);
210
211                                 glVertex2fv(tf->uv[1]);
212                                 glVertex2fv(tf->uv[2]);
213
214                                 if(!mf->v4) {
215                                         glVertex2fv(tf->uv[2]);
216                                         glVertex2fv(tf->uv[0]);
217                                 } else {
218                                         glVertex2fv(tf->uv[2]);
219                                         glVertex2fv(tf->uv[3]);
220
221                                         glVertex2fv(tf->uv[3]);
222                                         glVertex2fv(tf->uv[0]);
223                                 }
224                         }
225                 }
226                 glEnd();
227         }
228 }
229
230 static void cdDM_drawEdges(DerivedMesh *dm, int drawLooseEdges)
231 {
232         CDDerivedMesh *cddm = (CDDerivedMesh*) dm;
233         MVert *mvert = cddm->mvert;
234         MEdge *medge = cddm->medge;
235         int i;
236                 
237         glBegin(GL_LINES);
238         for(i = 0; i < dm->numEdgeData; i++, medge++) {
239                 if((medge->flag&ME_EDGEDRAW)
240                    && (drawLooseEdges || !(medge->flag&ME_LOOSEEDGE))) {
241                         glVertex3fv(mvert[medge->v1].co);
242                         glVertex3fv(mvert[medge->v2].co);
243                 }
244         }
245         glEnd();
246 }
247
248 static void cdDM_drawLooseEdges(DerivedMesh *dm)
249 {
250         CDDerivedMesh *cddm = (CDDerivedMesh*) dm;
251         MVert *mvert = cddm->mvert;
252         MEdge *medge = cddm->medge;
253         int i;
254
255         glBegin(GL_LINES);
256         for(i = 0; i < dm->numEdgeData; i++, medge++) {
257                 if(medge->flag&ME_LOOSEEDGE) {
258                         glVertex3fv(mvert[medge->v1].co);
259                         glVertex3fv(mvert[medge->v2].co);
260                 }
261         }
262         glEnd();
263 }
264
265 static void cdDM_drawFacesSolid(DerivedMesh *dm, int (*setMaterial)(int, void *attribs))
266 {
267         CDDerivedMesh *cddm = (CDDerivedMesh*) dm;
268         MVert *mvert = cddm->mvert;
269         MFace *mface = cddm->mface;
270         float *nors= dm->getTessFaceDataArray(dm, CD_NORMAL);
271         int a, glmode = -1, shademodel = -1, matnr = -1, drawCurrentMat = 1;
272
273 #define PASSVERT(index) {                                               \
274         if(shademodel == GL_SMOOTH) {                           \
275                 short *no = mvert[index].no;                    \
276                 glNormal3sv(no);                                                \
277         }                                                                                       \
278         glVertex3fv(mvert[index].co);   \
279 }
280
281         glBegin(glmode = GL_QUADS);
282         for(a = 0; a < dm->numFaceData; a++, mface++) {
283                 int new_glmode, new_matnr, new_shademodel;
284
285                 new_glmode = mface->v4?GL_QUADS:GL_TRIANGLES;
286                 new_matnr = mface->mat_nr + 1;
287                 new_shademodel = (mface->flag & ME_SMOOTH)?GL_SMOOTH:GL_FLAT;
288                 
289                 if(new_glmode != glmode || new_matnr != matnr
290                    || new_shademodel != shademodel) {
291                         glEnd();
292
293                         drawCurrentMat = setMaterial(matnr = new_matnr, NULL);
294
295                         glShadeModel(shademodel = new_shademodel);
296                         glBegin(glmode = new_glmode);
297                 } 
298                 
299                 if(drawCurrentMat) {
300                         if(shademodel == GL_FLAT) {
301                                 if (nors) {
302                                         glNormal3fv(nors);
303                                 }
304                                 else {
305                                         /* TODO make this better (cache facenormals as layer?) */
306                                         float nor[3];
307                                         if(mface->v4) {
308                                                 CalcNormFloat4(mvert[mface->v1].co, mvert[mface->v2].co,
309                                                                            mvert[mface->v3].co, mvert[mface->v4].co,
310                                                                            nor);
311                                         } else {
312                                                 CalcNormFloat(mvert[mface->v1].co, mvert[mface->v2].co,
313                                                                           mvert[mface->v3].co, nor);
314                                         }
315                                         glNormal3fv(nor);
316                                 }
317                         }
318
319                         PASSVERT(mface->v1);
320                         PASSVERT(mface->v2);
321                         PASSVERT(mface->v3);
322                         if(mface->v4) {
323                                 PASSVERT(mface->v4);
324                         }
325                 }
326
327                 if(nors) nors += 3;
328         }
329         glEnd();
330
331         glShadeModel(GL_FLAT);
332 #undef PASSVERT
333 }
334
335 static void cdDM_drawFacesColored(DerivedMesh *dm, int useTwoSided, unsigned char *col1, unsigned char *col2)
336 {
337         CDDerivedMesh *cddm = (CDDerivedMesh*) dm;
338         int a, glmode;
339         unsigned char *cp1, *cp2;
340         MVert *mvert = cddm->mvert;
341         MFace *mface = cddm->mface;
342
343         cp1 = col1;
344         if(col2) {
345                 cp2 = col2;
346         } else {
347                 cp2 = NULL;
348                 useTwoSided = 0;
349         }
350
351         /* there's a conflict here... twosided colors versus culling...? */
352         /* defined by history, only texture faces have culling option */
353         /* we need that as mesh option builtin, next to double sided lighting */
354         if(col1 && col2)
355                 glEnable(GL_CULL_FACE);
356         
357         glShadeModel(GL_SMOOTH);
358         glBegin(glmode = GL_QUADS);
359         for(a = 0; a < dm->numFaceData; a++, mface++, cp1 += 16) {
360                 int new_glmode = mface->v4?GL_QUADS:GL_TRIANGLES;
361
362                 if(new_glmode != glmode) {
363                         glEnd();
364                         glBegin(glmode = new_glmode);
365                 }
366                         
367                 glColor3ub(cp1[0], cp1[1], cp1[2]);
368                 glVertex3fv(mvert[mface->v1].co);
369                 glColor3ub(cp1[4], cp1[5], cp1[6]);
370                 glVertex3fv(mvert[mface->v2].co);
371                 glColor3ub(cp1[8], cp1[9], cp1[10]);
372                 glVertex3fv(mvert[mface->v3].co);
373                 if(mface->v4) {
374                         glColor3ub(cp1[12], cp1[13], cp1[14]);
375                         glVertex3fv(mvert[mface->v4].co);
376                 }
377                         
378                 if(useTwoSided) {
379                         glColor3ub(cp2[8], cp2[9], cp2[10]);
380                         glVertex3fv(mvert[mface->v3].co );
381                         glColor3ub(cp2[4], cp2[5], cp2[6]);
382                         glVertex3fv(mvert[mface->v2].co );
383                         glColor3ub(cp2[0], cp2[1], cp2[2]);
384                         glVertex3fv(mvert[mface->v1].co );
385                         if(mface->v4) {
386                                 glColor3ub(cp2[12], cp2[13], cp2[14]);
387                                 glVertex3fv(mvert[mface->v4].co );
388                         }
389                 }
390                 if(col2) cp2 += 16;
391         }
392         glEnd();
393
394         glShadeModel(GL_FLAT);
395         glDisable(GL_CULL_FACE);
396 }
397
398 static void cdDM_drawFacesTex_common(DerivedMesh *dm,
399                int (*drawParams)(MTFace *tface, int has_vcol, int matnr),
400                int (*drawParamsMapped)(void *userData, int index),
401                void *userData) 
402 {
403         CDDerivedMesh *cddm = (CDDerivedMesh*) dm;
404         MVert *mv = cddm->mvert;
405         MFace *mf = cddm->mface;
406         MCol *mcol = dm->getTessFaceDataArray(dm, CD_MCOL);
407         float *nors= dm->getTessFaceDataArray(dm, CD_NORMAL);
408         MTFace *tf = DM_get_tessface_data_layer(dm, CD_MTFACE);
409         int i, orig, *index = DM_get_tessface_data_layer(dm, CD_ORIGINDEX);
410
411         for(i = 0; i < dm->numFaceData; i++, mf++) {
412                 MVert *mvert;
413                 int flag;
414                 unsigned char *cp = NULL;
415
416                 if(drawParams) {
417                         flag = drawParams(tf? &tf[i]: NULL, mcol != NULL, mf->mat_nr);
418                 }
419                 else {
420                         if(index) {
421                                 orig = *index++;
422                                 if(orig == ORIGINDEX_NONE)              { if(nors) nors += 3; continue; }
423                                 if(drawParamsMapped) flag = drawParamsMapped(userData, orig);
424                                 else    { if(nors) nors += 3; continue; }
425                         }
426                         else
427                                 if(drawParamsMapped) flag = drawParamsMapped(userData, i);
428                                 else    { if(nors) nors += 3; continue; }
429                 }
430                 
431                 if(flag != 0) { /* if the flag is 0 it means the face is hidden or invisible */
432                         if (flag==1 && mcol)
433                                 cp= (unsigned char*) &mcol[i*4];
434
435                         if(!(mf->flag&ME_SMOOTH)) {
436                                 if (nors) {
437                                         glNormal3fv(nors);
438                                 }
439                                 else {
440                                         /* TODO make this better (cache facenormals as layer?) */
441                                         float nor[3];
442                                         if(mf->v4) {
443                                                 CalcNormFloat4(mv[mf->v1].co, mv[mf->v2].co,
444                                                                            mv[mf->v3].co, mv[mf->v4].co,
445                                                                            nor);
446                                         } else {
447                                                 CalcNormFloat(mv[mf->v1].co, mv[mf->v2].co,
448                                                                           mv[mf->v3].co, nor);
449                                         }
450                                         glNormal3fv(nor);
451                                 }
452                         }
453
454                         glBegin(mf->v4?GL_QUADS:GL_TRIANGLES);
455                         if(tf) glTexCoord2fv(tf[i].uv[0]);
456                         if(cp) glColor3ub(cp[3], cp[2], cp[1]);
457                         mvert = &mv[mf->v1];
458                         if(mf->flag&ME_SMOOTH) glNormal3sv(mvert->no);
459                         glVertex3fv(mvert->co);
460                                 
461                         if(tf) glTexCoord2fv(tf[i].uv[1]);
462                         if(cp) glColor3ub(cp[7], cp[6], cp[5]);
463                         mvert = &mv[mf->v2];
464                         if(mf->flag&ME_SMOOTH) glNormal3sv(mvert->no);
465                         glVertex3fv(mvert->co);
466
467                         if(tf) glTexCoord2fv(tf[i].uv[2]);
468                         if(cp) glColor3ub(cp[11], cp[10], cp[9]);
469                         mvert = &mv[mf->v3];
470                         if(mf->flag&ME_SMOOTH) glNormal3sv(mvert->no);
471                         glVertex3fv(mvert->co);
472
473                         if(mf->v4) {
474                                 if(tf) glTexCoord2fv(tf[i].uv[3]);
475                                 if(cp) glColor3ub(cp[15], cp[14], cp[13]);
476                                 mvert = &mv[mf->v4];
477                                 if(mf->flag&ME_SMOOTH) glNormal3sv(mvert->no);
478                                 glVertex3fv(mvert->co);
479                         }
480                         glEnd();
481                 }
482                 
483                 if(nors) nors += 3;
484         }
485 }
486
487 static void cdDM_drawFacesTex(DerivedMesh *dm, int (*setDrawOptions)(MTFace *tface, int has_vcol, int matnr))
488 {
489         cdDM_drawFacesTex_common(dm, setDrawOptions, NULL, NULL);
490 }
491
492 static void cdDM_drawMappedFaces(DerivedMesh *dm, int (*setDrawOptions)(void *userData, int index, int *drawSmooth_r), void *userData, int useColors)
493 {
494         CDDerivedMesh *cddm = (CDDerivedMesh*) dm;
495         MVert *mv = cddm->mvert;
496         MFace *mf = cddm->mface;
497         MCol *mc;
498         float *nors= dm->getTessFaceDataArray(dm, CD_NORMAL);
499         int i, orig, *index = DM_get_tessface_data_layer(dm, CD_ORIGINDEX);
500
501         mc = DM_get_tessface_data_layer(dm, CD_WEIGHT_MCOL);
502         if(!mc)
503                 mc = DM_get_tessface_data_layer(dm, CD_MCOL);
504
505         for(i = 0; i < dm->numFaceData; i++, mf++) {
506                 int drawSmooth = (mf->flag & ME_SMOOTH);
507
508                 if(index) {
509                         orig = *index++;
510                         if(setDrawOptions && orig == ORIGINDEX_NONE)
511                                 { if(nors) nors += 3; continue; }
512                 }
513                 else
514                         orig = i;
515
516                 if(!setDrawOptions || setDrawOptions(userData, orig, &drawSmooth)) {
517                         unsigned char *cp = NULL;
518
519                         if(useColors && mc)
520                                 cp = (unsigned char *)&mc[i * 4];
521
522                         glShadeModel(drawSmooth?GL_SMOOTH:GL_FLAT);
523                         glBegin(mf->v4?GL_QUADS:GL_TRIANGLES);
524
525                         if (!drawSmooth) {
526                                 if (nors) {
527                                         glNormal3fv(nors);
528                                 }
529                                 else {
530                                         /* TODO make this better (cache facenormals as layer?) */
531                                         float nor[3];
532                                         if(mf->v4) {
533                                                 CalcNormFloat4(mv[mf->v1].co, mv[mf->v2].co,
534                                                                            mv[mf->v3].co, mv[mf->v4].co,
535                                                                            nor);
536                                         } else {
537                                                 CalcNormFloat(mv[mf->v1].co, mv[mf->v2].co,
538                                                                           mv[mf->v3].co, nor);
539                                         }
540                                         glNormal3fv(nor);
541                                 }
542
543                                 if(cp) glColor3ub(cp[3], cp[2], cp[1]);
544                                 glVertex3fv(mv[mf->v1].co);
545                                 if(cp) glColor3ub(cp[7], cp[6], cp[5]);
546                                 glVertex3fv(mv[mf->v2].co);
547                                 if(cp) glColor3ub(cp[11], cp[10], cp[9]);
548                                 glVertex3fv(mv[mf->v3].co);
549                                 if(mf->v4) {
550                                         if(cp) glColor3ub(cp[15], cp[14], cp[13]);
551                                         glVertex3fv(mv[mf->v4].co);
552                                 }
553                         } else {
554                                 if(cp) glColor3ub(cp[3], cp[2], cp[1]);
555                                 glNormal3sv(mv[mf->v1].no);
556                                 glVertex3fv(mv[mf->v1].co);
557                                 if(cp) glColor3ub(cp[7], cp[6], cp[5]);
558                                 glNormal3sv(mv[mf->v2].no);
559                                 glVertex3fv(mv[mf->v2].co);
560                                 if(cp) glColor3ub(cp[11], cp[10], cp[9]);
561                                 glNormal3sv(mv[mf->v3].no);
562                                 glVertex3fv(mv[mf->v3].co);
563                                 if(mf->v4) {
564                                         if(cp) glColor3ub(cp[15], cp[14], cp[13]);
565                                         glNormal3sv(mv[mf->v4].no);
566                                         glVertex3fv(mv[mf->v4].co);
567                                 }
568                         }
569
570                         glEnd();
571                 }
572                 
573                 if (nors) nors += 3;
574         }
575 }
576
577 static void cdDM_drawMappedFacesTex(DerivedMesh *dm, int (*setDrawOptions)(void *userData, int index), void *userData)
578 {
579         cdDM_drawFacesTex_common(dm, NULL, setDrawOptions, userData);
580 }
581
582 static void cdDM_drawMappedFacesGLSL(DerivedMesh *dm, int (*setMaterial)(int, void *attribs), int (*setDrawOptions)(void *userData, int index), void *userData)
583 {
584         CDDerivedMesh *cddm = (CDDerivedMesh*) dm;
585         GPUVertexAttribs gattribs;
586         DMVertexAttribs attribs;
587         MVert *mvert = cddm->mvert;
588         MFace *mface = cddm->mface;
589         MTFace *tf = dm->getTessFaceDataArray(dm, CD_MTFACE);
590         float (*nors)[3] = dm->getTessFaceDataArray(dm, CD_NORMAL);
591         int a, b, dodraw, smoothnormal, matnr, new_matnr;
592         int transp, new_transp, orig_transp;
593         int orig, *index = dm->getTessFaceDataArray(dm, CD_ORIGINDEX);
594
595         matnr = -1;
596         smoothnormal = 0;
597         dodraw = 0;
598         transp = GPU_get_material_blend_mode();
599         orig_transp = transp;
600
601         memset(&attribs, 0, sizeof(attribs));
602
603         glShadeModel(GL_SMOOTH);
604         glBegin(GL_QUADS);
605
606         for(a = 0; a < dm->numFaceData; a++, mface++) {
607                 new_matnr = mface->mat_nr + 1;
608
609                 if(new_matnr != matnr) {
610                         glEnd();
611
612                         dodraw = setMaterial(matnr = new_matnr, &gattribs);
613                         if(dodraw)
614                                 DM_vertex_attributes_from_gpu(dm, &gattribs, &attribs);
615
616                         glBegin(GL_QUADS);
617                 }
618
619                 if(!dodraw) {
620                         continue;
621                 }
622                 else if(setDrawOptions) {
623                         orig = index[a];
624
625                         if(orig == ORIGINDEX_NONE)
626                                 continue;
627                         else if(!setDrawOptions(userData, orig))
628                                 continue;
629                 }
630
631                 if(tf) {
632                         new_transp = tf[a].transp;
633
634                         if(new_transp != transp) {
635                                 glEnd();
636
637                                 if(new_transp == GPU_BLEND_SOLID && orig_transp != GPU_BLEND_SOLID)
638                                         GPU_set_material_blend_mode(orig_transp);
639                                 else
640                                         GPU_set_material_blend_mode(new_transp);
641                                 transp = new_transp;
642
643                                 glBegin(GL_QUADS);
644                         }
645                 }
646
647                 smoothnormal = (mface->flag & ME_SMOOTH);
648
649                 if(!smoothnormal) {
650                         if(nors) {
651                                 glNormal3fv(nors[a]);
652                         }
653                         else {
654                                 /* TODO ideally a normal layer should always be available */
655                                 float nor[3];
656                                 if(mface->v4) {
657                                         CalcNormFloat4(mvert[mface->v1].co, mvert[mface->v2].co,
658                                                                    mvert[mface->v3].co, mvert[mface->v4].co,
659                                                                    nor);
660                                 } else {
661                                         CalcNormFloat(mvert[mface->v1].co, mvert[mface->v2].co,
662                                                                   mvert[mface->v3].co, nor);
663                                 }
664                                 glNormal3fv(nor);
665                         }
666                 }
667
668 #define PASSVERT(index, vert) {                                                                                                 \
669         if(attribs.totorco)                                                                                                                     \
670                 glVertexAttrib3fvARB(attribs.orco.glIndex, attribs.orco.array[index]);  \
671         for(b = 0; b < attribs.tottface; b++) {                                                                         \
672                 MTFace *tf = &attribs.tface[b].array[a];                                                                \
673                 glVertexAttrib2fvARB(attribs.tface[b].glIndex, tf->uv[vert]);                   \
674         }                                                                                                                                                       \
675         for(b = 0; b < attribs.totmcol; b++) {                                                                          \
676                 MCol *cp = &attribs.mcol[b].array[a*4 + vert];                                                  \
677                 GLubyte col[4];                                                                                                                 \
678                 col[0]= cp->b; col[1]= cp->g; col[2]= cp->r; col[3]= cp->a;                             \
679                 glVertexAttrib4ubvARB(attribs.mcol[b].glIndex, col);                                    \
680         }                                                                                                                                                       \
681         if(attribs.tottang) {                                                                                                           \
682                 float *tang = attribs.tang.array[a*4 + vert];                                                   \
683                 glVertexAttrib3fvARB(attribs.tang.glIndex, tang);                                               \
684         }                                                                                                                                                       \
685         if(smoothnormal)                                                                                                                        \
686                 glNormal3sv(mvert[index].no);                                                                                   \
687         glVertex3fv(mvert[index].co);                                                                                           \
688 }
689
690                 PASSVERT(mface->v1, 0);
691                 PASSVERT(mface->v2, 1);
692                 PASSVERT(mface->v3, 2);
693                 if(mface->v4)
694                         PASSVERT(mface->v4, 3)
695                 else
696                         PASSVERT(mface->v3, 2)
697
698 #undef PASSVERT
699         }
700         glEnd();
701
702         glShadeModel(GL_FLAT);
703 }
704
705 static void cdDM_drawFacesGLSL(DerivedMesh *dm, int (*setMaterial)(int, void *attribs))
706 {
707         dm->drawMappedFacesGLSL(dm, setMaterial, NULL, NULL);
708 }
709
710 static void cdDM_drawMappedEdges(DerivedMesh *dm, int (*setDrawOptions)(void *userData, int index), void *userData)
711 {
712         CDDerivedMesh *cddm = (CDDerivedMesh*) dm;
713         MVert *vert = cddm->mvert;
714         MEdge *edge = cddm->medge;
715         int i, orig, *index = DM_get_edge_data_layer(dm, CD_ORIGINDEX);
716
717         glBegin(GL_LINES);
718         for(i = 0; i < dm->numEdgeData; i++, edge++) {
719                 if(index) {
720                         orig = *index++;
721                         if(setDrawOptions && orig == ORIGINDEX_NONE) continue;
722                 }
723                 else
724                         orig = i;
725
726                 if(!setDrawOptions || setDrawOptions(userData, orig)) {
727                         glVertex3fv(vert[edge->v1].co);
728                         glVertex3fv(vert[edge->v2].co);
729                 }
730         }
731         glEnd();
732 }
733
734 static void cdDM_foreachMappedVert(
735                            DerivedMesh *dm,
736                            void (*func)(void *userData, int index, float *co,
737                                         float *no_f, short *no_s),
738                            void *userData)
739 {
740         MVert *mv = CDDM_get_verts(dm);
741         int i, orig, *index = DM_get_vert_data_layer(dm, CD_ORIGINDEX);
742
743         for(i = 0; i < dm->numVertData; i++, mv++) {
744                 if(index) {
745                         orig = *index++;
746                         if(orig == ORIGINDEX_NONE) continue;
747                         func(userData, orig, mv->co, NULL, mv->no);
748                 }
749                 else
750                         func(userData, i, mv->co, NULL, mv->no);
751         }
752 }
753
754 static void cdDM_foreachMappedEdge(
755                            DerivedMesh *dm,
756                            void (*func)(void *userData, int index,
757                                         float *v0co, float *v1co),
758                            void *userData)
759 {
760         CDDerivedMesh *cddm = (CDDerivedMesh*) dm;
761         MVert *mv = cddm->mvert;
762         MEdge *med = cddm->medge;
763         int i, orig, *index = DM_get_edge_data_layer(dm, CD_ORIGINDEX);
764
765         for(i = 0; i < dm->numEdgeData; i++, med++) {
766                 if (index) {
767                         orig = *index++;
768                         if(orig == ORIGINDEX_NONE) continue;
769                         func(userData, orig, mv[med->v1].co, mv[med->v2].co);
770                 }
771                 else
772                         func(userData, i, mv[med->v1].co, mv[med->v2].co);
773         }
774 }
775
776 static void cdDM_foreachMappedFaceCenter(
777                            DerivedMesh *dm,
778                            void (*func)(void *userData, int index,
779                                         float *cent, float *no),
780                            void *userData)
781 {
782         CDDerivedMesh *cddm = (CDDerivedMesh*)dm;
783         MVert *mv = cddm->mvert;
784         MPoly *mf = cddm->mpoly;
785         MLoop *ml = cddm->mloop;
786         int i, j, orig, *index;
787         int maxf=0;
788
789         index = CustomData_get_layer(&dm->polyData, CD_ORIGINDEX);
790         mf = cddm->mpoly;
791         for(i = 0; i < dm->numPolyData; i++, mf++) {
792                 float cent[3];
793                 float no[3];
794
795                 if (index) {
796                         orig = *index++;
797                         if(orig == ORIGINDEX_NONE) continue;
798                 } else
799                         orig = i;
800                 
801                 ml = &cddm->mloop[mf->loopstart];
802                 cent[0] = cent[1] = cent[2] = 0.0f;
803                 for (j=0; j<mf->totloop; j++, ml++) {
804                         VecAddf(cent, cent, mv[ml->v].co);
805                 }
806                 VecMulf(cent, 1.0f / (float)j);
807
808                 ml = &cddm->mloop[mf->loopstart];
809                 if (j > 3) {
810                         CalcNormFloat4(mv[ml->v].co, mv[(ml+1)->v].co,
811                                        mv[(ml+2)->v].co, mv[(ml+3)->v].co, no);
812                 } else {
813                         CalcNormFloat(mv[ml->v].co, mv[(ml+1)->v].co,
814                                        mv[(ml+2)->v].co, no);
815                 }
816
817                 func(userData, orig, cent, no);
818         }
819
820 }
821
822 static void cdDM_recalcTesselation(DerivedMesh *dm)
823 {
824         CDDerivedMesh *cddm = (CDDerivedMesh*)dm;
825
826         dm->numFaceData = mesh_recalcTesselation(&dm->faceData, &dm->loopData, 
827                 &dm->polyData, cddm->mvert, dm->numFaceData, dm->numLoopData, dm->numPolyData);
828         
829         cddm->mface = CustomData_get_layer(&dm->faceData, CD_MFACE);
830 }
831
832 static void cdDM_release(DerivedMesh *dm)
833 {
834         CDDerivedMesh *cddm = (CDDerivedMesh*)dm;
835
836         if (DM_release(dm))
837                 MEM_freeN(cddm);
838 }
839
840 int CDDM_Check(DerivedMesh *dm)
841 {
842         return dm && dm->getMinMax == cdDM_getMinMax;
843 }
844
845 /**************** CDDM interface functions ****************/
846 static CDDerivedMesh *cdDM_create(const char *desc)
847 {
848         CDDerivedMesh *cddm;
849         DerivedMesh *dm;
850
851         cddm = MEM_callocN(sizeof(*cddm), desc);
852         dm = &cddm->dm;
853
854         dm->getMinMax = cdDM_getMinMax;
855
856         dm->getNumVerts = cdDM_getNumVerts;
857         dm->getNumEdges = cdDM_getNumEdges;
858         dm->getNumTessFaces = cdDM_getNumTessFaces;
859         dm->getNumFaces = cdDM_getNumFaces;
860
861         dm->newFaceIter = cdDM_newFaceIter;
862
863         dm->getVert = cdDM_getVert;
864         dm->getEdge = cdDM_getEdge;
865         dm->getTessFace = cdDM_getFace;
866         dm->copyVertArray = cdDM_copyVertArray;
867         dm->copyEdgeArray = cdDM_copyEdgeArray;
868         dm->copyTessFaceArray = cdDM_copyFaceArray;
869         dm->getVertData = DM_get_vert_data;
870         dm->getEdgeData = DM_get_edge_data;
871         dm->getTessFaceData = DM_get_face_data;
872         dm->getVertDataArray = DM_get_vert_data_layer;
873         dm->getEdgeDataArray = DM_get_edge_data_layer;
874         dm->getTessFaceDataArray = DM_get_tessface_data_layer;
875         
876         //doesn't work yet for all cases
877         //dm->recalcTesselation = cdDM_recalcTesselation;
878
879         dm->getVertCos = cdDM_getVertCos;
880         dm->getVertCo = cdDM_getVertCo;
881         dm->getVertNo = cdDM_getVertNo;
882
883         dm->drawVerts = cdDM_drawVerts;
884
885         dm->drawUVEdges = cdDM_drawUVEdges;
886         dm->drawEdges = cdDM_drawEdges;
887         dm->drawLooseEdges = cdDM_drawLooseEdges;
888         dm->drawMappedEdges = cdDM_drawMappedEdges;
889
890         dm->drawFacesSolid = cdDM_drawFacesSolid;
891         dm->drawFacesColored = cdDM_drawFacesColored;
892         dm->drawFacesTex = cdDM_drawFacesTex;
893         dm->drawFacesGLSL = cdDM_drawFacesGLSL;
894         dm->drawMappedFaces = cdDM_drawMappedFaces;
895         dm->drawMappedFacesTex = cdDM_drawMappedFacesTex;
896         dm->drawMappedFacesGLSL = cdDM_drawMappedFacesGLSL;
897
898         dm->foreachMappedVert = cdDM_foreachMappedVert;
899         dm->foreachMappedEdge = cdDM_foreachMappedEdge;
900         dm->foreachMappedFaceCenter = cdDM_foreachMappedFaceCenter;
901
902         dm->release = cdDM_release;
903
904         return cddm;
905 }
906
907 DerivedMesh *CDDM_new(int numVerts, int numEdges, int numFaces, int numLoops, int numPolys)
908 {
909         CDDerivedMesh *cddm = cdDM_create("CDDM_new dm");
910         DerivedMesh *dm = &cddm->dm;
911
912         DM_init(dm, numVerts, numEdges, numFaces, numLoops, numPolys);
913
914         CustomData_add_layer(&dm->vertData, CD_ORIGINDEX, CD_CALLOC, NULL, numVerts);
915         CustomData_add_layer(&dm->edgeData, CD_ORIGINDEX, CD_CALLOC, NULL, numEdges);
916         CustomData_add_layer(&dm->faceData, CD_ORIGINDEX, CD_CALLOC, NULL, numFaces);
917         CustomData_add_layer(&dm->polyData, CD_ORIGINDEX, CD_CALLOC, NULL, numPolys);
918
919         CustomData_add_layer(&dm->vertData, CD_MVERT, CD_CALLOC, NULL, numVerts);
920         CustomData_add_layer(&dm->edgeData, CD_MEDGE, CD_CALLOC, NULL, numEdges);
921         CustomData_add_layer(&dm->faceData, CD_MFACE, CD_CALLOC, NULL, numFaces);
922         CustomData_add_layer(&dm->loopData, CD_MLOOP, CD_CALLOC, NULL, numLoops);
923         CustomData_add_layer(&dm->polyData, CD_MPOLY, CD_CALLOC, NULL, numPolys);
924
925         cddm->mvert = CustomData_get_layer(&dm->vertData, CD_MVERT);
926         cddm->medge = CustomData_get_layer(&dm->edgeData, CD_MEDGE);
927         cddm->mface = CustomData_get_layer(&dm->faceData, CD_MFACE);
928         cddm->mloop = CustomData_get_layer(&dm->loopData, CD_MLOOP);
929         cddm->mpoly = CustomData_get_layer(&dm->polyData, CD_MPOLY);
930
931         return dm;
932 }
933
934 DerivedMesh *CDDM_from_mesh(Mesh *mesh, Object *ob)
935 {
936         CDDerivedMesh *cddm = cdDM_create("CDDM_from_mesh dm");
937         DerivedMesh *dm = &cddm->dm;
938         CustomDataMask mask = CD_MASK_MESH & (~CD_MASK_MDISPS);
939         int i, *index, alloctype;
940
941         /* this does a referenced copy, the only new layers being ORIGINDEX,
942          * with an exception for fluidsim */
943
944         DM_init(dm, mesh->totvert, mesh->totedge, mesh->totface,
945                     mesh->totloop, mesh->totpoly);
946
947         CustomData_add_layer(&dm->vertData, CD_ORIGINDEX, CD_CALLOC, NULL, mesh->totvert);
948         CustomData_add_layer(&dm->edgeData, CD_ORIGINDEX, CD_CALLOC, NULL, mesh->totedge);
949         CustomData_add_layer(&dm->polyData, CD_ORIGINDEX, CD_CALLOC, NULL, mesh->totpoly);
950
951         dm->deformedOnly = 1;
952
953         alloctype= CD_REFERENCE;
954
955         CustomData_merge(&mesh->vdata, &dm->vertData, mask, alloctype,
956                          mesh->totvert);
957         CustomData_merge(&mesh->edata, &dm->edgeData, mask, alloctype,
958                          mesh->totedge);
959         CustomData_merge(&mesh->fdata, &dm->faceData, mask|CD_MASK_ORIGINDEX, alloctype,
960                          mesh->totface);
961         CustomData_merge(&mesh->ldata, &dm->loopData, mask, alloctype,
962                          mesh->totloop);
963         CustomData_merge(&mesh->pdata, &dm->polyData, mask, alloctype,
964                          mesh->totpoly);
965
966         cddm->mvert = CustomData_get_layer(&dm->vertData, CD_MVERT);
967         cddm->medge = CustomData_get_layer(&dm->edgeData, CD_MEDGE);
968         cddm->mloop = CustomData_get_layer(&dm->loopData, CD_MLOOP);
969         cddm->mpoly = CustomData_get_layer(&dm->polyData, CD_MPOLY);
970         cddm->mface = CustomData_get_layer(&dm->faceData, CD_MFACE);
971
972         index = CustomData_get_layer(&dm->vertData, CD_ORIGINDEX);
973         for(i = 0; i < mesh->totvert; ++i, ++index)
974                 *index = i;
975
976         index = CustomData_get_layer(&dm->edgeData, CD_ORIGINDEX);
977         for(i = 0; i < mesh->totedge; ++i, ++index)
978                 *index = i;
979
980         index = CustomData_get_layer(&dm->polyData, CD_ORIGINDEX);
981         for(i = 0; i < mesh->totpoly; ++i, ++index)
982                 *index = i;
983
984         if (!CustomData_has_layer(&cddm->dm.faceData, CD_ORIGINDEX))
985                 CustomData_add_layer(&dm->faceData, CD_ORIGINDEX, CD_CALLOC, NULL, mesh->totface);
986
987         return dm;
988 }
989
990 DerivedMesh *CDDM_from_editmesh(EditMesh *em, Mesh *me)
991 {
992         DerivedMesh *dm = CDDM_new(BLI_countlist(&em->verts),
993                                    BLI_countlist(&em->edges),
994                                    BLI_countlist(&em->faces), 0, 0);
995         CDDerivedMesh *cddm = (CDDerivedMesh*)dm;
996         EditVert *eve;
997         EditEdge *eed;
998         EditFace *efa;
999         MVert *mvert = cddm->mvert;
1000         MEdge *medge = cddm->medge;
1001         MFace *mface = cddm->mface;
1002         int i, *index;
1003
1004         dm->deformedOnly = 1;
1005
1006         CustomData_merge(&em->vdata, &dm->vertData, CD_MASK_DERIVEDMESH,
1007                          CD_CALLOC, dm->numVertData);
1008         /* CustomData_merge(&em->edata, &dm->edgeData, CD_MASK_DERIVEDMESH,
1009                          CD_CALLOC, dm->numEdgeData); */
1010         CustomData_merge(&em->fdata, &dm->faceData, CD_MASK_DERIVEDMESH,
1011                          CD_CALLOC, dm->numFaceData);
1012         CustomData_merge(&em->fdata, &dm->faceData, CD_MASK_DERIVEDMESH,
1013                          CD_CALLOC, dm->numFaceData);
1014
1015         /* set eve->hash to vert index */
1016         for(i = 0, eve = em->verts.first; eve; eve = eve->next, ++i)
1017                 eve->tmp.l = i;
1018
1019         /* Need to be able to mark loose edges */
1020         for(eed = em->edges.first; eed; eed = eed->next) {
1021                 eed->f2 = 0;
1022         }
1023         for(efa = em->faces.first; efa; efa = efa->next) {
1024                 efa->e1->f2 = 1;
1025                 efa->e2->f2 = 1;
1026                 efa->e3->f2 = 1;
1027                 if(efa->e4) efa->e4->f2 = 1;
1028         }
1029
1030         index = dm->getVertDataArray(dm, CD_ORIGINDEX);
1031         for(i = 0, eve = em->verts.first; i < dm->numVertData;
1032             i++, eve = eve->next, index++) {
1033                 MVert *mv = &mvert[i];
1034
1035                 VECCOPY(mv->co, eve->co);
1036
1037                 mv->no[0] = eve->no[0] * 32767.0;
1038                 mv->no[1] = eve->no[1] * 32767.0;
1039                 mv->no[2] = eve->no[2] * 32767.0;
1040                 mv->bweight = (unsigned char) (eve->bweight * 255.0f);
1041
1042                 mv->mat_nr = 0;
1043                 mv->flag = 0;
1044
1045                 *index = i;
1046
1047                 CustomData_from_em_block(&em->vdata, &dm->vertData, eve->data, i);
1048         }
1049
1050         index = dm->getEdgeDataArray(dm, CD_ORIGINDEX);
1051         for(i = 0, eed = em->edges.first; i < dm->numEdgeData;
1052             i++, eed = eed->next, index++) {
1053                 MEdge *med = &medge[i];
1054
1055                 med->v1 = eed->v1->tmp.l;
1056                 med->v2 = eed->v2->tmp.l;
1057                 med->crease = (unsigned char) (eed->crease * 255.0f);
1058                 med->bweight = (unsigned char) (eed->bweight * 255.0f);
1059                 med->flag = ME_EDGEDRAW|ME_EDGERENDER;
1060                 
1061                 if(eed->seam) med->flag |= ME_SEAM;
1062                 if(eed->sharp) med->flag |= ME_SHARP;
1063                 if(!eed->f2) med->flag |= ME_LOOSEEDGE;
1064
1065                 *index = i;
1066
1067                 /* CustomData_from_em_block(&em->edata, &dm->edgeData, eed->data, i); */
1068         }
1069
1070         index = dm->getTessFaceDataArray(dm, CD_ORIGINDEX);
1071         for(i = 0, efa = em->faces.first; i < dm->numFaceData;
1072             i++, efa = efa->next, index++) {
1073                 MFace *mf = &mface[i];
1074
1075                 mf->v1 = efa->v1->tmp.l;
1076                 mf->v2 = efa->v2->tmp.l;
1077                 mf->v3 = efa->v3->tmp.l;
1078                 mf->v4 = efa->v4 ? efa->v4->tmp.l : 0;
1079                 mf->mat_nr = efa->mat_nr;
1080                 mf->flag = efa->flag;
1081
1082                 *index = i;
1083
1084                 CustomData_from_em_block(&em->fdata, &dm->faceData, efa->data, i);
1085                 test_index_face(mf, &dm->faceData, i, efa->v4?4:3);
1086         }
1087
1088         return dm;
1089 }
1090
1091
1092 static void loops_to_customdata_corners(BMesh *bm, CustomData *facedata,
1093                                       int cdindex, BMLoop *l3[3],
1094                                       int numCol, int numTex)
1095 {
1096         BMLoop *l;
1097         BMFace *f = l3[0]->f;
1098         MTFace *texface;
1099         MTexPoly *texpoly;
1100         MCol *mcol;
1101         MLoopCol *mloopcol;
1102         MLoopUV *mloopuv;
1103         int i, j, hasWCol = CustomData_has_layer(&bm->ldata, CD_WEIGHT_MLOOPCOL);
1104
1105         for(i=0; i < numTex; i++){
1106                 texface = CustomData_get_n(facedata, CD_MTFACE, cdindex, i);
1107                 texpoly = CustomData_bmesh_get_n(&bm->pdata, f->head.data, CD_MTEXPOLY, i);
1108                 
1109                 texface->tpage = texpoly->tpage;
1110                 texface->flag = texpoly->flag;
1111                 texface->transp = texpoly->transp;
1112                 texface->mode = texpoly->mode;
1113                 texface->tile = texpoly->tile;
1114                 texface->unwrap = texpoly->unwrap;
1115         
1116                 for (j=0; j<3; j++) {
1117                         l = l3[j];
1118                         mloopuv = CustomData_bmesh_get_n(&bm->ldata, l->head.data, CD_MLOOPUV, i);
1119                         texface->uv[j][0] = mloopuv->uv[0];
1120                         texface->uv[j][1] = mloopuv->uv[1];
1121                 }
1122         }
1123
1124         for(i=0; i < numCol; i++){
1125                 mcol = CustomData_get_n(facedata, CD_MCOL, cdindex, i);
1126                 
1127                 for (j=0; j<3; j++) {
1128                         l = l3[j];
1129                         mloopcol = CustomData_bmesh_get_n(&bm->ldata, l->head.data, CD_MLOOPCOL, i);
1130                         mcol[j].r = mloopcol->r;
1131                         mcol[j].g = mloopcol->g;
1132                         mcol[j].b = mloopcol->b;
1133                         mcol[j].a = mloopcol->a;
1134                 }
1135         }
1136
1137         if (hasWCol) {
1138                 mcol = CustomData_get(facedata, cdindex, CD_WEIGHT_MCOL);
1139
1140                 for (j=0; j<3; j++) {
1141                         l = l3[j];
1142                         mloopcol = CustomData_bmesh_get(&bm->ldata, l->head.data, CD_WEIGHT_MLOOPCOL);
1143                         mcol[j].r = mloopcol->r;
1144                         mcol[j].g = mloopcol->g;
1145                         mcol[j].b = mloopcol->b;
1146                         mcol[j].a = mloopcol->a;
1147                 }
1148         }
1149 }
1150
1151 DerivedMesh *CDDM_from_BMEditMesh(BMEditMesh *em, Mesh *me)
1152 {
1153         DerivedMesh *dm = CDDM_new(em->bm->totvert, em->bm->totedge, 
1154                                em->tottri, em->bm->totloop, em->bm->totface);
1155         CDDerivedMesh *cddm = (CDDerivedMesh*)dm;
1156         BMesh *bm = em->bm;
1157         BMIter iter, liter;
1158         BMVert *eve;
1159         BMEdge *eed;
1160         BMFace *efa;
1161         MVert *mvert = cddm->mvert;
1162         MEdge *medge = cddm->medge;
1163         MFace *mface = cddm->mface;
1164         MLoop *mloop = cddm->mloop;
1165         MPoly *mpoly = cddm->mpoly;
1166         int numCol = CustomData_number_of_layers(&em->bm->ldata, CD_MLOOPCOL);
1167         int numTex = CustomData_number_of_layers(&em->bm->pdata, CD_MTEXPOLY);
1168         int i, j, *index, add_orig;
1169
1170         dm->deformedOnly = 1;
1171         
1172         /*don't add origindex layer if one already exists*/
1173         add_orig = !CustomData_has_layer(&em->bm->pdata, CD_ORIGINDEX);
1174
1175         CustomData_merge(&em->bm->vdata, &dm->vertData, CD_MASK_DERIVEDMESH,
1176                          CD_CALLOC, dm->numVertData);
1177         CustomData_merge(&em->bm->edata, &dm->edgeData, CD_MASK_DERIVEDMESH,
1178                          CD_CALLOC, dm->numEdgeData);
1179         CustomData_merge(&em->bm->pdata, &dm->faceData, CD_MASK_DERIVEDMESH,
1180                          CD_CALLOC, dm->numFaceData);
1181         CustomData_merge(&em->bm->ldata, &dm->loopData, CD_MASK_DERIVEDMESH,
1182                          CD_CALLOC, dm->numLoopData);
1183         CustomData_merge(&em->bm->pdata, &dm->polyData, CD_MASK_DERIVEDMESH,
1184                          CD_CALLOC, dm->numPolyData);
1185         
1186         /*add tesselation mface layers*/
1187         CustomData_from_bmeshpoly(&dm->faceData, &dm->polyData, &dm->loopData, em->tottri);
1188
1189         /* set vert index */
1190         eve = BMIter_New(&iter, bm, BM_VERTS_OF_MESH, NULL);
1191         for (i=0; eve; eve=BMIter_Step(&iter), i++)
1192                 BMINDEX_SET(eve, i);
1193
1194         index = dm->getVertDataArray(dm, CD_ORIGINDEX);
1195
1196         eve = BMIter_New(&iter, bm, BM_VERTS_OF_MESH, NULL);
1197         for (i=0; eve; eve=BMIter_Step(&iter), i++, index++) {
1198                 MVert *mv = &mvert[i];
1199
1200                 VECCOPY(mv->co, eve->co);
1201
1202                 BMINDEX_SET(eve, i);
1203
1204                 mv->no[0] = eve->no[0] * 32767.0;
1205                 mv->no[1] = eve->no[1] * 32767.0;
1206                 mv->no[2] = eve->no[2] * 32767.0;
1207                 mv->bweight = (unsigned char) (eve->bweight * 255.0f);
1208
1209                 mv->mat_nr = 0;
1210                 mv->flag = BMFlags_To_MEFlags(eve);
1211
1212                 if (add_orig) *index = i;
1213
1214                 CustomData_from_bmesh_block(&bm->vdata, &dm->vertData, eve->head.data, i);
1215         }
1216
1217         index = dm->getEdgeDataArray(dm, CD_ORIGINDEX);
1218         eed = BMIter_New(&iter, bm, BM_EDGES_OF_MESH, NULL);
1219         for (i=0; eed; eed=BMIter_Step(&iter), i++, index++) {
1220                 MEdge *med = &medge[i];
1221
1222                 BMINDEX_SET(eed, i);
1223
1224                 med->v1 = BMINDEX_GET(eed->v1);
1225                 med->v2 = BMINDEX_GET(eed->v2);
1226                 med->crease = (unsigned char) (eed->crease * 255.0f);
1227                 med->bweight = (unsigned char) (eed->bweight * 255.0f);
1228                 med->flag = ME_EDGEDRAW|ME_EDGERENDER;
1229                 
1230                 med->flag = BMFlags_To_MEFlags(eed);
1231
1232                 CustomData_from_bmesh_block(&bm->edata, &dm->edgeData, eed->head.data, i);
1233                 if (add_orig) *index = i;
1234         }
1235
1236         efa = BMIter_New(&iter, bm, BM_FACES_OF_MESH, NULL);
1237         for (i=0; efa; i++, efa=BMIter_Step(&iter)) {
1238                 BMINDEX_SET(efa, i);
1239         }
1240
1241         index = dm->getTessFaceDataArray(dm, CD_ORIGINDEX);
1242         for(i = 0; i < dm->numFaceData; i++, index++) {
1243                 MFace *mf = &mface[i];
1244                 BMLoop **l = em->looptris[i];
1245                 efa = l[0]->f;
1246
1247                 mf->v1 = BMINDEX_GET(l[0]->v);
1248                 mf->v2 = BMINDEX_GET(l[1]->v);
1249                 mf->v3 = BMINDEX_GET(l[2]->v);
1250                 mf->v4 = 0;
1251                 mf->mat_nr = efa->mat_nr;
1252                 mf->flag = BMFlags_To_MEFlags(efa);
1253                 
1254                 *index = add_orig ? BMINDEX_GET(efa) : *(int*)CustomData_bmesh_get(&bm->pdata, efa->head.data, CD_ORIGINDEX);
1255
1256                 loops_to_customdata_corners(bm, &dm->faceData, i, l, numCol, numTex);
1257                 test_index_face(mf, &dm->faceData, i, 3);
1258         }
1259         
1260         index = CustomData_get_layer(&dm->polyData, CD_ORIGINDEX);
1261         j = 0;
1262         efa = BMIter_New(&iter, bm, BM_FACES_OF_MESH, NULL);
1263         for (i=0; efa; i++, efa=BMIter_Step(&iter), index++) {
1264                 BMLoop *l;
1265                 MPoly *mp = &mpoly[i];
1266
1267                 mp->totloop = efa->len;
1268                 mp->flag = BMFlags_To_MEFlags(efa);
1269                 mp->loopstart = j;
1270                 mp->mat_nr = efa->mat_nr;
1271                 
1272                 BM_ITER(l, &liter, bm, BM_LOOPS_OF_FACE, efa) {
1273                         mloop->v = BMINDEX_GET(l->v);
1274                         mloop->e = BMINDEX_GET(l->e);
1275                         CustomData_from_bmesh_block(&bm->ldata, &dm->loopData, l->head.data, j);
1276
1277                         j++;
1278                         mloop++;
1279                 }
1280
1281                 CustomData_from_bmesh_block(&bm->pdata, &dm->polyData, efa->head.data, i);
1282
1283                 if (add_orig) *index = i;
1284         }
1285
1286         return dm;
1287 }
1288
1289 typedef struct CDDM_LoopIter {
1290         DMLoopIter head;
1291         CDDerivedMesh *cddm;
1292         int len, i;
1293 } CDDM_LoopIter;
1294
1295 typedef struct CDDM_FaceIter {
1296         DMFaceIter head;
1297         CDDerivedMesh *cddm;
1298         CDDM_LoopIter liter;
1299 } CDDM_FaceIter;
1300
1301 void cddm_freeiter(void *self)
1302 {
1303         MEM_freeN(self);
1304 }
1305
1306 void cddm_stepiter(void *self)
1307 {
1308         CDDM_FaceIter *iter = self;
1309         MPoly *mp;
1310         
1311         iter->head.index++;
1312         if (iter->head.index >= iter->cddm->dm.numPolyData) {
1313                 iter->head.done = 1;
1314                 return;
1315         }
1316
1317         mp = iter->cddm->mpoly + iter->head.index;
1318
1319         iter->head.flags = mp->flag;
1320         iter->head.mat_nr = mp->mat_nr;
1321         iter->head.len = mp->totloop;
1322 }
1323
1324 void *cddm_faceiter_getcddata(void *self, int type, int layer)
1325 {
1326         CDDM_FaceIter *iter = self;
1327
1328         if (layer == -1) return CustomData_get(&iter->cddm->dm.polyData, 
1329                                                iter->head.index, type);
1330         else return CustomData_get_n(&iter->cddm->dm.polyData, type, 
1331                                     iter->head.index, layer);
1332 }
1333
1334 void *cddm_loopiter_getcddata(void *self, int type, int layer)
1335 {
1336         CDDM_LoopIter *iter = self;
1337
1338         if (layer == -1) return CustomData_get(&iter->cddm->dm.loopData, 
1339                                                iter->head.index, type);
1340         else return CustomData_get_n(&iter->cddm->dm.loopData, type, 
1341                                      iter->head.index, layer);
1342 }
1343
1344 void *cddm_loopiter_getvertcddata(void *self, int type, int layer)
1345 {
1346         CDDM_LoopIter *iter = self;
1347
1348         if (layer == -1) return CustomData_get(&iter->cddm->dm.vertData, 
1349                                                iter->cddm->mloop[iter->head.vindex].v,
1350                                                type);
1351         else return CustomData_get_n(&iter->cddm->dm.vertData, type, 
1352                                      iter->cddm->mloop[iter->head.vindex].v, layer);
1353 }
1354
1355 DMLoopIter *cddmiter_get_loopiter(void *self)
1356 {
1357         CDDM_FaceIter *iter = self;
1358         CDDM_LoopIter *liter = &iter->liter;
1359         MPoly *mp = iter->cddm->mpoly + iter->head.index;
1360
1361         liter->i = -1;
1362         liter->len = iter->head.len;
1363         liter->head.index = mp->loopstart-1;
1364         liter->head.done = 0;
1365
1366         liter->head.step(liter);
1367
1368         return (DMLoopIter*) liter;
1369 }
1370
1371 void cddm_loopiter_step(void *self)
1372 {
1373         CDDM_LoopIter *liter = self;
1374         MLoop *ml;
1375
1376         liter->i++;
1377         liter->head.index++;
1378
1379         if (liter->i == liter->len) {
1380                 liter->head.done = 1;
1381                 return;
1382         }
1383
1384         ml = liter->cddm->mloop + liter->head.index;
1385
1386         liter->head.eindex = ml->e;
1387         liter->head.v = liter->cddm->mvert[ml->v];
1388         liter->head.vindex = ml->v;
1389 }
1390
1391 DMFaceIter *cdDM_newFaceIter(DerivedMesh *source)
1392 {
1393         CDDerivedMesh *cddm = (CDDerivedMesh*) source;
1394         CDDM_FaceIter *iter = MEM_callocN(sizeof(CDDM_FaceIter), "DMFaceIter from cddm");
1395
1396         iter->head.free = cddm_freeiter;
1397         iter->head.step = cddm_stepiter;
1398         iter->head.getCDData = cddm_faceiter_getcddata;
1399         iter->head.getLoopsIter = cddmiter_get_loopiter;
1400
1401         iter->liter.head.step = cddm_loopiter_step;
1402         iter->liter.head.getLoopCDData = cddm_loopiter_getcddata;
1403         iter->liter.head.getVertCDData = cddm_loopiter_getvertcddata;
1404         iter->liter.cddm = cddm;
1405
1406         iter->cddm = cddm;
1407         iter->head.index = -1;
1408         iter->head.step(iter);
1409
1410         return (DMFaceIter*) iter;
1411 }
1412
1413 DerivedMesh *CDDM_copy(DerivedMesh *source, int faces_from_tessfaces)
1414 {
1415         CDDerivedMesh *cddm = cdDM_create("CDDM_copy cddm");
1416         DerivedMesh *dm = &cddm->dm;
1417         int numVerts = source->numVertData;
1418         int numEdges = source->numEdgeData;
1419         int numFaces = source->numFaceData;
1420         int numLoops = source->numLoopData;
1421         int numPolys = source->numPolyData;
1422
1423         /* this initializes dm, and copies all non mvert/medge/mface layers */
1424         DM_from_template(dm, source, numVerts, numEdges, numFaces,
1425                 numLoops, numPolys);
1426         dm->deformedOnly = source->deformedOnly;
1427
1428         CustomData_copy_data(&source->vertData, &dm->vertData, 0, 0, numVerts);
1429         CustomData_copy_data(&source->edgeData, &dm->edgeData, 0, 0, numEdges);
1430         CustomData_copy_data(&source->faceData, &dm->faceData, 0, 0, numFaces);
1431
1432         /* now add mvert/medge/mface layers */
1433         cddm->mvert = source->dupVertArray(source);
1434         cddm->medge = source->dupEdgeArray(source);
1435         cddm->mface = source->dupTessFaceArray(source);
1436
1437         CustomData_add_layer(&dm->vertData, CD_MVERT, CD_ASSIGN, cddm->mvert, numVerts);
1438         CustomData_add_layer(&dm->edgeData, CD_MEDGE, CD_ASSIGN, cddm->medge, numEdges);
1439         CustomData_add_layer(&dm->faceData, CD_MFACE, CD_ASSIGN, cddm->mface, numFaces);
1440         
1441         if (!faces_from_tessfaces)
1442                 DM_DupPolys(source, dm);
1443         else
1444                 CDDM_tessfaces_to_faces(dm);
1445
1446         cddm->mloop = CustomData_get_layer(&dm->loopData, CD_MLOOP);
1447         cddm->mpoly = CustomData_get_layer(&dm->polyData, CD_MPOLY);
1448
1449         return dm;
1450 }
1451
1452 DerivedMesh *CDDM_from_template(DerivedMesh *source,
1453                                 int numVerts, int numEdges, int numFaces,
1454                                 int numLoops, int numPolys)
1455 {
1456         CDDerivedMesh *cddm = cdDM_create("CDDM_from_template dest");
1457         DerivedMesh *dm = &cddm->dm;
1458
1459         /* this does a copy of all non mvert/medge/mface layers */
1460         DM_from_template(dm, source, numVerts, numEdges, numFaces, numLoops, numPolys);
1461
1462         /* now add mvert/medge/mface layers */
1463         CustomData_add_layer(&dm->vertData, CD_MVERT, CD_CALLOC, NULL, numVerts);
1464         CustomData_add_layer(&dm->edgeData, CD_MEDGE, CD_CALLOC, NULL, numEdges);
1465         CustomData_add_layer(&dm->faceData, CD_MFACE, CD_CALLOC, NULL, numFaces);
1466         CustomData_add_layer(&dm->loopData, CD_MLOOP, CD_CALLOC, NULL, numLoops);
1467         CustomData_add_layer(&dm->polyData, CD_MPOLY, CD_CALLOC, NULL, numPolys);
1468
1469         cddm->mvert = CustomData_get_layer(&dm->vertData, CD_MVERT);
1470         cddm->medge = CustomData_get_layer(&dm->edgeData, CD_MEDGE);
1471         cddm->mface = CustomData_get_layer(&dm->faceData, CD_MFACE);
1472         cddm->mloop = CustomData_get_layer(&dm->loopData, CD_MLOOP);
1473         cddm->mpoly = CustomData_get_layer(&dm->polyData, CD_MPOLY);
1474
1475         return dm;
1476 }
1477
1478 void CDDM_apply_vert_coords(DerivedMesh *dm, float (*vertCoords)[3])
1479 {
1480         CDDerivedMesh *cddm = (CDDerivedMesh*)dm;
1481         MVert *vert;
1482         int i;
1483
1484         /* this will just return the pointer if it wasn't a referenced layer */
1485         vert = CustomData_duplicate_referenced_layer(&dm->vertData, CD_MVERT);
1486         cddm->mvert = vert;
1487
1488         for(i = 0; i < dm->numVertData; ++i, ++vert)
1489                 VECCOPY(vert->co, vertCoords[i]);
1490 }
1491
1492 void CDDM_apply_vert_normals(DerivedMesh *dm, short (*vertNormals)[3])
1493 {
1494         CDDerivedMesh *cddm = (CDDerivedMesh*)dm;
1495         MVert *vert;
1496         int i;
1497
1498         /* this will just return the pointer if it wasn't a referenced layer */
1499         vert = CustomData_duplicate_referenced_layer(&dm->vertData, CD_MVERT);
1500         cddm->mvert = vert;
1501
1502         for(i = 0; i < dm->numVertData; ++i, ++vert)
1503                 VECCOPY(vert->no, vertNormals[i]);
1504 }
1505
1506 /* adapted from mesh_calc_normals */
1507 void CDDM_calc_normals(DerivedMesh *dm)
1508 {
1509         CDDerivedMesh *cddm = (CDDerivedMesh*)dm;
1510         float (*temp_nors)[3];
1511         float (*face_nors)[3];
1512         int i;
1513         int numVerts = dm->numVertData;
1514         int numFaces = dm->numFaceData;
1515         MFace *mf;
1516         MVert *mv;
1517
1518         if(numVerts == 0) return;
1519
1520         temp_nors = MEM_callocN(numVerts * sizeof(*temp_nors),
1521                                 "CDDM_calc_normals temp_nors");
1522
1523         /* we don't want to overwrite any referenced layers */
1524         mv = CustomData_duplicate_referenced_layer(&dm->vertData, CD_MVERT);
1525         cddm->mvert = mv;
1526
1527         /* make a face normal layer if not present */
1528         face_nors = CustomData_get_layer(&dm->faceData, CD_NORMAL);
1529         if(!face_nors)
1530                 face_nors = CustomData_add_layer(&dm->faceData, CD_NORMAL, CD_CALLOC,
1531                                                  NULL, dm->numFaceData);
1532
1533         /* calculate face normals and add to vertex normals */
1534         mf = CDDM_get_tessfaces(dm);
1535         for(i = 0; i < numFaces; i++, mf++) {
1536                 float *f_no = face_nors[i];
1537
1538                 if(mf->v4)
1539                         CalcNormFloat4(mv[mf->v1].co, mv[mf->v2].co,
1540                                        mv[mf->v3].co, mv[mf->v4].co, f_no);
1541                 else
1542                         CalcNormFloat(mv[mf->v1].co, mv[mf->v2].co,
1543                                       mv[mf->v3].co, f_no);
1544                 
1545                 VecAddf(temp_nors[mf->v1], temp_nors[mf->v1], f_no);
1546                 VecAddf(temp_nors[mf->v2], temp_nors[mf->v2], f_no);
1547                 VecAddf(temp_nors[mf->v3], temp_nors[mf->v3], f_no);
1548                 if(mf->v4)
1549                         VecAddf(temp_nors[mf->v4], temp_nors[mf->v4], f_no);
1550         }
1551
1552         /* normalize vertex normals and assign */
1553         for(i = 0; i < numVerts; i++, mv++) {
1554                 float *no = temp_nors[i];
1555                 
1556                 if (Normalize(no) == 0.0) {
1557                         VECCOPY(no, mv->co);
1558                         Normalize(no);
1559                 }
1560
1561                 mv->no[0] = (short)(no[0] * 32767.0);
1562                 mv->no[1] = (short)(no[1] * 32767.0);
1563                 mv->no[2] = (short)(no[2] * 32767.0);
1564         }
1565         
1566         MEM_freeN(temp_nors);
1567 }
1568
1569 void CDDM_calc_edges(DerivedMesh *dm)
1570 {
1571         CDDerivedMesh *cddm = (CDDerivedMesh*)dm;
1572         CustomData edgeData;
1573         EdgeHashIterator *ehi;
1574         MFace *mf = cddm->mface;
1575         MEdge *med;
1576         EdgeHash *eh = BLI_edgehash_new();
1577         int i, *index, numEdges, maxFaces = dm->numFaceData;
1578
1579         for (i = 0; i < maxFaces; i++, mf++) {
1580                 if (!BLI_edgehash_haskey(eh, mf->v1, mf->v2))
1581                         BLI_edgehash_insert(eh, mf->v1, mf->v2, NULL);
1582                 if (!BLI_edgehash_haskey(eh, mf->v2, mf->v3))
1583                         BLI_edgehash_insert(eh, mf->v2, mf->v3, NULL);
1584                 
1585                 if (mf->v4) {
1586                         if (!BLI_edgehash_haskey(eh, mf->v3, mf->v4))
1587                                 BLI_edgehash_insert(eh, mf->v3, mf->v4, NULL);
1588                         if (!BLI_edgehash_haskey(eh, mf->v4, mf->v1))
1589                                 BLI_edgehash_insert(eh, mf->v4, mf->v1, NULL);
1590                 } else {
1591                         if (!BLI_edgehash_haskey(eh, mf->v3, mf->v1))
1592                                 BLI_edgehash_insert(eh, mf->v3, mf->v1, NULL);
1593                 }
1594         }
1595
1596         numEdges = BLI_edgehash_size(eh);
1597
1598         /* write new edges into a temporary CustomData */
1599         memset(&edgeData, 0, sizeof(edgeData));
1600         CustomData_add_layer(&edgeData, CD_MEDGE, CD_CALLOC, NULL, numEdges);
1601         CustomData_add_layer(&edgeData, CD_ORIGINDEX, CD_CALLOC, NULL, numEdges);
1602
1603         ehi = BLI_edgehashIterator_new(eh);
1604         med = CustomData_get_layer(&edgeData, CD_MEDGE);
1605         index = CustomData_get_layer(&edgeData, CD_ORIGINDEX);
1606         for(i = 0; !BLI_edgehashIterator_isDone(ehi);
1607             BLI_edgehashIterator_step(ehi), ++i, ++med, ++index) {
1608                 BLI_edgehashIterator_getKey(ehi, (int*)&med->v1, (int*)&med->v2);
1609
1610                 med->flag = ME_EDGEDRAW|ME_EDGERENDER;
1611                 *index = ORIGINDEX_NONE;
1612         }
1613         BLI_edgehashIterator_free(ehi);
1614
1615         /* free old CustomData and assign new one */
1616         CustomData_free(&dm->edgeData, dm->numEdgeData);
1617         dm->edgeData = edgeData;
1618         dm->numEdgeData = numEdges;
1619
1620         cddm->medge = CustomData_get_layer(&dm->edgeData, CD_MEDGE);
1621
1622         BLI_edgehash_free(eh, NULL);
1623 }
1624
1625
1626 void CDDM_calc_edges_poly(DerivedMesh *dm)
1627 {
1628         CDDerivedMesh *cddm = (CDDerivedMesh*)dm;
1629         CustomData edgeData;
1630         EdgeHashIterator *ehi;
1631         MPoly *mp = cddm->mpoly;
1632         MLoop *ml;
1633         MEdge *med;
1634         EdgeHash *eh = BLI_edgehash_new();
1635         int v1, v2;
1636         int *eindex;
1637         int i, j, k, *index, numEdges = cddm->dm.numEdgeData, maxFaces = dm->numPolyData;
1638
1639         eindex = DM_get_edge_data_layer(dm, CD_ORIGINDEX);
1640
1641         med = cddm->medge;
1642         if (med) {
1643                 for (i=0; i < numEdges; i++, med++) {
1644                         BLI_edgehash_insert(eh, med->v1, med->v2, SET_INT_IN_POINTER(i+1));
1645                 }
1646         }
1647
1648         for (i=0; i < maxFaces; i++, mp++) {
1649                 ml = cddm->mloop + mp->loopstart;
1650                 for (j=0; j<mp->totloop; j++, ml++) {
1651                         v1 = ml->v;
1652                         v2 = (cddm->mloop + mp->loopstart + ((j+1)%mp->totloop))->v;
1653                         if (!BLI_edgehash_haskey(eh, v1, v2)) {
1654                                 BLI_edgehash_insert(eh, v1, v2, NULL);
1655                         }
1656                 }
1657         }
1658
1659         k = numEdges;
1660         numEdges = BLI_edgehash_size(eh);
1661
1662         /* write new edges into a temporary CustomData */
1663         memset(&edgeData, 0, sizeof(edgeData));
1664         CustomData_add_layer(&edgeData, CD_MEDGE, CD_CALLOC, NULL, numEdges);
1665         CustomData_add_layer(&edgeData, CD_ORIGINDEX, CD_CALLOC, NULL, numEdges);
1666
1667         ehi = BLI_edgehashIterator_new(eh);
1668         med = CustomData_get_layer(&edgeData, CD_MEDGE);
1669         index = CustomData_get_layer(&edgeData, CD_ORIGINDEX);
1670         for(i = 0; !BLI_edgehashIterator_isDone(ehi);
1671             BLI_edgehashIterator_step(ehi), ++i, ++med, ++index) {
1672                 BLI_edgehashIterator_getKey(ehi, (int*)&med->v1, (int*)&med->v2);
1673                 j = GET_INT_FROM_POINTER(BLI_edgehashIterator_getValue(ehi));
1674
1675                 med->flag = ME_EDGEDRAW|ME_EDGERENDER;
1676                 *index = j==0 ? ORIGINDEX_NONE : eindex[j-1];
1677
1678                 BLI_edgehashIterator_setValue(ehi, SET_INT_IN_POINTER(i));
1679         }
1680         BLI_edgehashIterator_free(ehi);
1681
1682         /* free old CustomData and assign new one */
1683         CustomData_free(&dm->edgeData, dm->numEdgeData);
1684         dm->edgeData = edgeData;
1685         dm->numEdgeData = numEdges;
1686
1687         cddm->medge = CustomData_get_layer(&dm->edgeData, CD_MEDGE);
1688
1689         mp = cddm->mpoly;
1690         for (i=0; i < maxFaces; i++, mp++) {
1691                 ml = cddm->mloop + mp->loopstart;
1692                 for (j=0; j<mp->totloop; j++, ml++) {
1693                         v1 = ml->v;
1694                         v2 = (cddm->mloop + mp->loopstart + ((j+1)%mp->totloop))->v;
1695                         ml->e = GET_INT_FROM_POINTER(BLI_edgehash_lookup(eh, v1, v2));
1696                 }
1697         }
1698
1699         BLI_edgehash_free(eh, NULL);
1700 }
1701
1702 void CDDM_lower_num_verts(DerivedMesh *dm, int numVerts)
1703 {
1704         if (numVerts < dm->numVertData)
1705                 CustomData_free_elem(&dm->vertData, numVerts, dm->numVertData-numVerts);
1706
1707         dm->numVertData = numVerts;
1708 }
1709
1710 void CDDM_lower_num_edges(DerivedMesh *dm, int numEdges)
1711 {
1712         if (numEdges < dm->numEdgeData)
1713                 CustomData_free_elem(&dm->edgeData, numEdges, dm->numEdgeData-numEdges);
1714
1715         dm->numEdgeData = numEdges;
1716 }
1717
1718 void CDDM_lower_num_faces(DerivedMesh *dm, int numFaces)
1719 {
1720         if (numFaces < dm->numFaceData)
1721                 CustomData_free_elem(&dm->faceData, numFaces, dm->numFaceData-numFaces);
1722
1723         dm->numFaceData = numFaces;
1724 }
1725
1726 MVert *CDDM_get_vert(DerivedMesh *dm, int index)
1727 {
1728         return &((CDDerivedMesh*)dm)->mvert[index];
1729 }
1730
1731 MEdge *CDDM_get_edge(DerivedMesh *dm, int index)
1732 {
1733         return &((CDDerivedMesh*)dm)->medge[index];
1734 }
1735
1736 MFace *CDDM_get_tessface(DerivedMesh *dm, int index)
1737 {
1738         return &((CDDerivedMesh*)dm)->mface[index];
1739 }
1740
1741 MVert *CDDM_get_verts(DerivedMesh *dm)
1742 {
1743         return ((CDDerivedMesh*)dm)->mvert;
1744 }
1745
1746 MEdge *CDDM_get_edges(DerivedMesh *dm)
1747 {
1748         return ((CDDerivedMesh*)dm)->medge;
1749 }
1750
1751 MFace *CDDM_get_tessfaces(DerivedMesh *dm)
1752 {
1753         return ((CDDerivedMesh*)dm)->mface;
1754 }
1755
1756 void CDDM_tessfaces_to_faces(DerivedMesh *dm)
1757 {
1758         /*converts mfaces to mpolys/mloops*/
1759         CDDerivedMesh *cddm = (CDDerivedMesh*)dm;
1760         MFace *mf;
1761         MEdge *me;
1762         MLoop *ml;
1763         MPoly *mp;
1764         EdgeHash *eh = BLI_edgehash_new();
1765         int i, l, totloop, *index1, *index2;
1766         
1767         /*ensure we have all the edges we need*/
1768         CDDM_calc_edges(dm);
1769
1770         /*build edge hash*/
1771         me = cddm->medge;
1772         for (i=0; i<cddm->dm.numEdgeData; i++, me++) {
1773                 BLI_edgehash_insert(eh, me->v1, me->v2, SET_INT_IN_POINTER(i));
1774         }
1775
1776         mf = cddm->mface;
1777         totloop = 0;
1778         for (i=0; i<cddm->dm.numFaceData; i++, mf++) {
1779                 totloop += mf->v4 ? 4 : 3;
1780         }
1781
1782         CustomData_free(&cddm->dm.polyData, cddm->dm.numPolyData);
1783         CustomData_free(&cddm->dm.loopData, cddm->dm.numLoopData);
1784         
1785         cddm->dm.numLoopData = totloop;
1786         cddm->dm.numPolyData = cddm->dm.numFaceData;
1787
1788         if (!totloop) return;
1789
1790         cddm->mloop = MEM_callocN(sizeof(MLoop)*totloop, "cddm->mloop in CDDM_tessfaces_to_faces");
1791         cddm->mpoly = MEM_callocN(sizeof(MPoly)*cddm->dm.numFaceData, "cddm->mpoly in CDDM_tessfaces_to_faces");
1792         
1793         CustomData_add_layer(&cddm->dm.loopData, CD_MLOOP, CD_ASSIGN, cddm->mloop, totloop);
1794         CustomData_add_layer(&cddm->dm.polyData, CD_MPOLY, CD_ASSIGN, cddm->mpoly, cddm->dm.numPolyData);
1795         CustomData_merge(&cddm->dm.faceData, &cddm->dm.polyData, 
1796                 CD_MASK_ORIGINDEX, CD_DUPLICATE, cddm->dm.numFaceData);
1797
1798         index1 = CustomData_get_layer(&cddm->dm.faceData, CD_ORIGINDEX);
1799         index2 = CustomData_get_layer(&cddm->dm.polyData, CD_ORIGINDEX);
1800
1801         mf = cddm->mface;
1802         mp = cddm->mpoly;
1803         ml = cddm->mloop;
1804         l = 0;
1805         for (i=0; i<cddm->dm.numFaceData; i++, mf++, mp++) {
1806                 mp->flag = mf->flag;
1807                 mp->loopstart = l;
1808                 mp->mat_nr = mf->mat_nr;
1809                 mp->totloop = mf->v4 ? 4 : 3;
1810                 
1811                 ml->v = mf->v1;
1812                 ml->e = GET_INT_FROM_POINTER(BLI_edgehash_lookup(eh, mf->v1, mf->v2));
1813                 ml++, l++;
1814
1815                 ml->v = mf->v2;
1816                 ml->e = GET_INT_FROM_POINTER(BLI_edgehash_lookup(eh, mf->v2, mf->v3));
1817                 ml++, l++;
1818
1819                 ml->v = mf->v3;
1820                 ml->e = GET_INT_FROM_POINTER(BLI_edgehash_lookup(eh, mf->v3, mf->v4?mf->v4:mf->v1));
1821                 ml++, l++;
1822
1823                 if (mf->v4) {
1824                         ml->v = mf->v4;
1825                         ml->e = GET_INT_FROM_POINTER(BLI_edgehash_lookup(eh, mf->v4, mf->v1));
1826                         ml++, l++;
1827                 }
1828
1829         }
1830
1831         BLI_edgehash_free(eh, NULL);
1832 }
1833
1834 void CDDM_set_mvert(DerivedMesh *dm, MVert *mvert)
1835 {
1836         CDDerivedMesh *cddm = (CDDerivedMesh*)dm;
1837         CustomData_add_layer(&cddm->dm.vertData, CD_MVERT, CD_ASSIGN, mvert, cddm->dm.numVertData);
1838         cddm->mvert = mvert;
1839 }
1840
1841 void CDDM_set_medge(DerivedMesh *dm, MEdge *medge)
1842 {
1843         CDDerivedMesh *cddm = (CDDerivedMesh*)dm;
1844         CustomData_add_layer(&cddm->dm.edgeData, CD_MEDGE, CD_ASSIGN, medge, cddm->dm.numEdgeData);
1845         cddm->medge = medge;
1846 }
1847
1848 void CDDM_set_mface(DerivedMesh *dm, MFace *mface)
1849 {
1850         CDDerivedMesh *cddm = (CDDerivedMesh*)dm;
1851         CustomData_add_layer(&cddm->dm.faceData, CD_MFACE, CD_ASSIGN, mface, cddm->dm.numFaceData);
1852         cddm->mface = mface;
1853 }
1854
1855 void CDDM_set_mloop(DerivedMesh *dm, MLoop *mloop)
1856 {
1857         CDDerivedMesh *cddm = (CDDerivedMesh*)dm;
1858         CustomData_add_layer(&cddm->dm.loopData, CD_MLOOP, CD_ASSIGN, mloop, cddm->dm.numLoopData);
1859         cddm->mloop = mloop;
1860 }
1861
1862 void CDDM_set_mpoly(DerivedMesh *dm, MPoly *mpoly)
1863 {
1864         CDDerivedMesh *cddm = (CDDerivedMesh*)dm;
1865         CustomData_add_layer(&cddm->dm.polyData, CD_MPOLY, CD_ASSIGN, mpoly, cddm->dm.numPolyData);
1866         cddm->mpoly = mpoly;
1867 }
1868
1869
1870 /* Multires DerivedMesh, extends CDDM */
1871 typedef struct MultiresDM {
1872         CDDerivedMesh cddm;
1873
1874         MultiresModifierData *mmd;
1875         int local_mmd;
1876
1877         int lvl, totlvl;
1878         float (*orco)[3];
1879         MVert *subco;
1880
1881         ListBase *vert_face_map, *vert_edge_map;
1882         IndexNode *vert_face_map_mem, *vert_edge_map_mem;
1883         int *face_offsets;
1884
1885         Object *ob;
1886         int modified;
1887
1888         void (*update)(DerivedMesh*);
1889 } MultiresDM;
1890
1891 static void MultiresDM_release(DerivedMesh *dm)
1892 {
1893         MultiresDM *mrdm = (MultiresDM*)dm;
1894         int mvert_layer;
1895
1896         /* Before freeing, need to update the displacement map */
1897         if(dm->needsFree && mrdm->modified) {
1898                 /* Check that mmd still exists */
1899                 if(!mrdm->local_mmd && BLI_findindex(&mrdm->ob->modifiers, mrdm->mmd) < 0)
1900                         mrdm->mmd = NULL;
1901                 if(mrdm->mmd)
1902                         mrdm->update(dm);
1903         }
1904
1905         /* If the MVert data is being used as the sculpt undo store, don't free it */
1906         mvert_layer = CustomData_get_layer_index(&dm->vertData, CD_MVERT);
1907         if(mvert_layer != -1) {
1908                 CustomDataLayer *cd = &dm->vertData.layers[mvert_layer];
1909                 if(mrdm->mmd && cd->data == mrdm->mmd->undo_verts)
1910                         cd->flag |= CD_FLAG_NOFREE;
1911         }
1912
1913         if(DM_release(dm)) {
1914                 MEM_freeN(mrdm->subco);
1915                 MEM_freeN(mrdm->orco);
1916                 if(mrdm->vert_face_map)
1917                         MEM_freeN(mrdm->vert_face_map);
1918                 if(mrdm->vert_face_map_mem)
1919                         MEM_freeN(mrdm->vert_face_map_mem);
1920                 if(mrdm->vert_edge_map)
1921                         MEM_freeN(mrdm->vert_edge_map);
1922                 if(mrdm->vert_edge_map_mem)
1923                         MEM_freeN(mrdm->vert_edge_map_mem);
1924                 if(mrdm->face_offsets)
1925                         MEM_freeN(mrdm->face_offsets);
1926                 MEM_freeN(mrdm);
1927         }
1928 }
1929
1930 DerivedMesh *MultiresDM_new(MultiresSubsurf *ms, DerivedMesh *orig, 
1931                             int numVerts, int numEdges, int numFaces,
1932                             int numLoops, int numPolys)
1933 {
1934         MultiresDM *mrdm = MEM_callocN(sizeof(MultiresDM), "MultiresDM");
1935         CDDerivedMesh *cddm = cdDM_create("MultiresDM CDDM");
1936         DerivedMesh *dm = NULL;
1937
1938         mrdm->cddm = *cddm;
1939         MEM_freeN(cddm);
1940         dm = &mrdm->cddm.dm;
1941
1942         mrdm->mmd = ms->mmd;
1943         mrdm->ob = ms->ob;
1944         mrdm->local_mmd = ms->local_mmd;
1945
1946         if(dm) {
1947                 MDisps *disps;
1948                 MVert *mvert;
1949                 int i;
1950
1951                 DM_from_template(dm, orig, numVerts, numEdges, numFaces, 
1952                                  numLoops, numPolys);
1953                 CustomData_free_layers(&dm->faceData, CD_MDISPS, numFaces);
1954
1955                 disps = CustomData_get_layer(&orig->faceData, CD_MDISPS);
1956                 if(disps)
1957                         CustomData_add_layer(&dm->faceData, CD_MDISPS, CD_REFERENCE, disps, numFaces);
1958
1959
1960                 mvert = CustomData_get_layer(&orig->vertData, CD_MVERT);
1961                 mrdm->orco = MEM_callocN(sizeof(float) * 3 * orig->getNumVerts(orig), "multires orco");
1962                 for(i = 0; i < orig->getNumVerts(orig); ++i)
1963                         VecCopyf(mrdm->orco[i], mvert[i].co);
1964         }
1965         else
1966                 DM_init(dm, numVerts, numEdges, numFaces, numLoops, numPolys);
1967
1968         CustomData_add_layer(&dm->vertData, CD_MVERT, CD_CALLOC, NULL, numVerts);
1969         CustomData_add_layer(&dm->edgeData, CD_MEDGE, CD_CALLOC, NULL, numEdges);
1970         CustomData_add_layer(&dm->faceData, CD_MFACE, CD_CALLOC, NULL, numFaces);
1971
1972         mrdm->cddm.mvert = CustomData_get_layer(&dm->vertData, CD_MVERT);
1973         mrdm->cddm.medge = CustomData_get_layer(&dm->edgeData, CD_MEDGE);
1974         mrdm->cddm.mface = CustomData_get_layer(&dm->faceData, CD_MFACE);
1975
1976         mrdm->lvl = ms->mmd->lvl;
1977         mrdm->totlvl = ms->mmd->totlvl;
1978         mrdm->subco = MEM_callocN(sizeof(MVert)*numVerts, "multires subdivided verts");
1979         mrdm->modified = 0;
1980
1981         dm->release = MultiresDM_release;
1982
1983         return dm;
1984 }
1985
1986 Mesh *MultiresDM_get_mesh(DerivedMesh *dm)
1987 {
1988         return get_mesh(((MultiresDM*)dm)->ob);
1989 }
1990
1991 Object *MultiresDM_get_object(DerivedMesh *dm)
1992 {
1993         return ((MultiresDM*)dm)->ob;
1994 }
1995
1996 void *MultiresDM_get_orco(DerivedMesh *dm)
1997 {
1998         return ((MultiresDM*)dm)->orco;
1999
2000 }
2001
2002 MVert *MultiresDM_get_subco(DerivedMesh *dm)
2003 {
2004         return ((MultiresDM*)dm)->subco;
2005 }
2006
2007 int MultiresDM_get_totlvl(DerivedMesh *dm)
2008 {
2009         return ((MultiresDM*)dm)->totlvl;
2010 }
2011
2012 int MultiresDM_get_lvl(DerivedMesh *dm)
2013 {
2014         return ((MultiresDM*)dm)->lvl;
2015 }
2016
2017 void MultiresDM_set_orco(DerivedMesh *dm, float (*orco)[3])
2018 {
2019         ((MultiresDM*)dm)->orco = orco;
2020 }
2021
2022 void MultiresDM_set_update(DerivedMesh *dm, void (*update)(DerivedMesh*))
2023 {
2024         ((MultiresDM*)dm)->update = update;
2025 }
2026
2027 ListBase *MultiresDM_get_vert_face_map(DerivedMesh *dm)
2028 {
2029         MultiresDM *mrdm = (MultiresDM*)dm;
2030         Mesh *me = mrdm->ob->data;
2031
2032         if(!mrdm->vert_face_map)
2033                 create_vert_face_map(&mrdm->vert_face_map, &mrdm->vert_face_map_mem, me->mface,
2034                                      me->totvert, me->totface);
2035
2036         return mrdm->vert_face_map;
2037 }
2038
2039 ListBase *MultiresDM_get_vert_edge_map(DerivedMesh *dm)
2040 {
2041         MultiresDM *mrdm = (MultiresDM*)dm;
2042         Mesh *me = mrdm->ob->data;
2043
2044         if(!mrdm->vert_edge_map)
2045                 create_vert_edge_map(&mrdm->vert_edge_map, &mrdm->vert_edge_map_mem, me->medge,
2046                                      me->totvert, me->totedge);
2047
2048         return mrdm->vert_edge_map;
2049 }
2050
2051 int *MultiresDM_get_face_offsets(DerivedMesh *dm)
2052 {
2053         MultiresDM *mrdm = (MultiresDM*)dm;
2054         Mesh *me = mrdm->ob->data;
2055         int i, accum = 0;
2056
2057         if(!mrdm->face_offsets) {
2058                 int len = (int)pow(2, mrdm->lvl - 2) - 1;
2059                 int area = len * len;
2060                 int t = 1 + len * 3 + area * 3, q = t + len + area;
2061
2062                 mrdm->face_offsets = MEM_callocN(sizeof(int) * me->totface, "mrdm face offsets");
2063                 for(i = 0; i < me->totface; ++i) {
2064                         mrdm->face_offsets[i] = accum;
2065
2066                         accum += (me->mface[i].v4 ? q : t);
2067                 }
2068         }
2069
2070         return mrdm->face_offsets;
2071 }
2072
2073 void MultiresDM_mark_as_modified(DerivedMesh *dm)
2074 {
2075         ((MultiresDM*)dm)->modified = 1;
2076 }
2077