svn merge ^/trunk/blender -r43482:43524
[blender.git] / source / blender / blenkernel / intern / DerivedMesh.c
index 5c80038a50dffb18db90e2aca309ae7a867c80f0..63605c14f6cb3cb5567bb4f1fb4714eff2d2fadd 100644 (file)
@@ -31,7 +31,7 @@
 
 
 #include <string.h>
 
 
 #include <string.h>
-
+#include "limits.h"
 
 #include "MEM_guardedalloc.h"
 
 
 #include "MEM_guardedalloc.h"
 
@@ -46,6 +46,7 @@
 #include "BLI_editVert.h"
 #include "BLI_math.h"
 #include "BLI_memarena.h"
 #include "BLI_editVert.h"
 #include "BLI_math.h"
 #include "BLI_memarena.h"
+#include "BLI_array.h"
 #include "BLI_pbvh.h"
 #include "BLI_utildefines.h"
 #include "BLI_linklist.h"
 #include "BLI_pbvh.h"
 #include "BLI_utildefines.h"
 #include "BLI_linklist.h"
@@ -60,6 +61,9 @@
 #include "BKE_texture.h"
 #include "BKE_multires.h"
 #include "BKE_armature.h"
 #include "BKE_texture.h"
 #include "BKE_multires.h"
 #include "BKE_armature.h"
+#include "BKE_particle.h"
+#include "BKE_tessmesh.h"
+#include "BKE_bvhutils.h"
 #include "BKE_deform.h"
 
 #ifdef WITH_GAMEENGINE
 #include "BKE_deform.h"
 
 #ifdef WITH_GAMEENGINE
@@ -78,6 +82,9 @@ static DerivedMesh *navmesh_dm_createNavMeshForVisualization(DerivedMesh *dm);
 
 extern GLubyte stipple_quarttone[128]; /* glutil.c, bad level data */
 
 
 extern GLubyte stipple_quarttone[128]; /* glutil.c, bad level data */
 
+static void add_shapekey_layers(DerivedMesh *dm, Mesh *me, Object *ob);
+static void shapekey_layers_to_keyblocks(DerivedMesh *dm, Mesh *me, int actshape_uid);
+
 ///////////////////////////////////
 ///////////////////////////////////
 
 ///////////////////////////////////
 ///////////////////////////////////
 
@@ -109,20 +116,48 @@ static MEdge *dm_getEdgeArray(DerivedMesh *dm)
        return medge;
 }
 
        return medge;
 }
 
-static MFace *dm_getFaceArray(DerivedMesh *dm)
+static MFace *dm_getTessFaceArray(DerivedMesh *dm)
 {
        MFace *mface = CustomData_get_layer(&dm->faceData, CD_MFACE);
 
        if (!mface) {
                mface = CustomData_add_layer(&dm->faceData, CD_MFACE, CD_CALLOC, NULL,
 {
        MFace *mface = CustomData_get_layer(&dm->faceData, CD_MFACE);
 
        if (!mface) {
                mface = CustomData_add_layer(&dm->faceData, CD_MFACE, CD_CALLOC, NULL,
-                       dm->getNumFaces(dm));
+                       dm->getNumTessFaces(dm));
                CustomData_set_layer_flag(&dm->faceData, CD_MFACE, CD_FLAG_TEMPORARY);
                CustomData_set_layer_flag(&dm->faceData, CD_MFACE, CD_FLAG_TEMPORARY);
-               dm->copyFaceArray(dm, mface);
+               dm->copyTessFaceArray(dm, mface);
        }
 
        return mface;
 }
 
        }
 
        return mface;
 }
 
+static MLoop *dm_getLoopArray(DerivedMesh *dm)
+{
+       MLoop *mloop = CustomData_get_layer(&dm->loopData, CD_MLOOP);
+
+       if (!mloop) {
+               mloop = CustomData_add_layer(&dm->loopData, CD_MLOOP, CD_CALLOC, NULL,
+                       dm->getNumLoops(dm));
+               CustomData_set_layer_flag(&dm->loopData, CD_MLOOP, CD_FLAG_TEMPORARY);
+               dm->copyLoopArray(dm, mloop);
+       }
+
+       return mloop;
+}
+
+static MPoly *dm_getPolyArray(DerivedMesh *dm)
+{
+       MPoly *mpoly = CustomData_get_layer(&dm->polyData, CD_MPOLY);
+
+       if (!mpoly) {
+               mpoly = CustomData_add_layer(&dm->polyData, CD_MPOLY, CD_CALLOC, NULL,
+                       dm->getNumPolys(dm));
+               CustomData_set_layer_flag(&dm->polyData, CD_MPOLY, CD_FLAG_TEMPORARY);
+               dm->copyPolyArray(dm, mpoly);
+       }
+
+       return mpoly;
+}
+
 static MVert *dm_dupVertArray(DerivedMesh *dm)
 {
        MVert *tmp = MEM_callocN(sizeof(*tmp) * dm->getNumVerts(dm),
 static MVert *dm_dupVertArray(DerivedMesh *dm)
 {
        MVert *tmp = MEM_callocN(sizeof(*tmp) * dm->getNumVerts(dm),
@@ -145,61 +180,126 @@ static MEdge *dm_dupEdgeArray(DerivedMesh *dm)
 
 static MFace *dm_dupFaceArray(DerivedMesh *dm)
 {
 
 static MFace *dm_dupFaceArray(DerivedMesh *dm)
 {
-       MFace *tmp = MEM_callocN(sizeof(*tmp) * dm->getNumFaces(dm),
+       MFace *tmp = MEM_callocN(sizeof(*tmp) * dm->getNumTessFaces(dm),
                                                         "dm_dupFaceArray tmp");
 
                                                         "dm_dupFaceArray tmp");
 
-       if(tmp) dm->copyFaceArray(dm, tmp);
+       if(tmp) dm->copyTessFaceArray(dm, tmp);
 
        return tmp;
 }
 
 
        return tmp;
 }
 
+static MLoop *dm_dupLoopArray(DerivedMesh *dm)
+{
+       MLoop *tmp = MEM_callocN(sizeof(*tmp) * dm->getNumLoops(dm),
+                                                        "dm_dupLoopArray tmp");
+
+       if(tmp) dm->copyLoopArray(dm, tmp);
+
+       return tmp;
+}
+
+static MPoly *dm_dupPolyArray(DerivedMesh *dm)
+{
+       MPoly *tmp = MEM_callocN(sizeof(*tmp) * dm->getNumPolys(dm),
+                                                        "dm_dupPolyArray tmp");
+
+       if(tmp) dm->copyPolyArray(dm, tmp);
+
+       return tmp;
+}
+
+static CustomData *dm_getVertCData(DerivedMesh *dm)
+{
+       return &dm->vertData;
+}
+
+static CustomData *dm_getEdgeCData(DerivedMesh *dm)
+{
+       return &dm->edgeData;
+}
+
+static CustomData *dm_getTessFaceCData(DerivedMesh *dm)
+{
+       return &dm->faceData;
+}
+
+static CustomData *dm_getLoopCData(DerivedMesh *dm)
+{
+       return &dm->loopData;
+}
+
+static CustomData *dm_getPolyCData(DerivedMesh *dm)
+{
+       return &dm->polyData;
+}
+
 void DM_init_funcs(DerivedMesh *dm)
 {
        /* default function implementations */
        dm->getVertArray = dm_getVertArray;
        dm->getEdgeArray = dm_getEdgeArray;
 void DM_init_funcs(DerivedMesh *dm)
 {
        /* default function implementations */
        dm->getVertArray = dm_getVertArray;
        dm->getEdgeArray = dm_getEdgeArray;
-       dm->getFaceArray = dm_getFaceArray;
+       dm->getTessFaceArray = dm_getTessFaceArray;
+       dm->getLoopArray = dm_getLoopArray;
+       dm->getPolyArray = dm_getPolyArray;
        dm->dupVertArray = dm_dupVertArray;
        dm->dupEdgeArray = dm_dupEdgeArray;
        dm->dupVertArray = dm_dupVertArray;
        dm->dupEdgeArray = dm_dupEdgeArray;
-       dm->dupFaceArray = dm_dupFaceArray;
+       dm->dupTessFaceArray = dm_dupFaceArray;
+       dm->dupLoopArray = dm_dupLoopArray;
+       dm->dupPolyArray = dm_dupPolyArray;
+
+       dm->getVertDataLayout = dm_getVertCData;
+       dm->getEdgeDataLayout = dm_getEdgeCData;
+       dm->getTessFaceDataLayout = dm_getTessFaceCData;
+       dm->getLoopDataLayout = dm_getLoopCData;
+       dm->getPolyDataLayout = dm_getPolyCData;
 
        dm->getVertData = DM_get_vert_data;
        dm->getEdgeData = DM_get_edge_data;
 
        dm->getVertData = DM_get_vert_data;
        dm->getEdgeData = DM_get_edge_data;
-       dm->getFaceData = DM_get_face_data;
+       dm->getTessFaceData = DM_get_tessface_data;
        dm->getVertDataArray = DM_get_vert_data_layer;
        dm->getEdgeDataArray = DM_get_edge_data_layer;
        dm->getVertDataArray = DM_get_vert_data_layer;
        dm->getEdgeDataArray = DM_get_edge_data_layer;
-       dm->getFaceDataArray = DM_get_face_data_layer;
+       dm->getTessFaceDataArray = DM_get_tessface_data_layer;
 
        bvhcache_init(&dm->bvhCache);
 }
 
 
        bvhcache_init(&dm->bvhCache);
 }
 
-void DM_init(DerivedMesh *dm, DerivedMeshType type,
-                        int numVerts, int numEdges, int numFaces)
+void DM_init(DerivedMesh *dm, DerivedMeshType type, int numVerts, int numEdges,
+            int numTessFaces, int numLoops, int numPolys)
 {
        dm->type = type;
        dm->numVertData = numVerts;
        dm->numEdgeData = numEdges;
 {
        dm->type = type;
        dm->numVertData = numVerts;
        dm->numEdgeData = numEdges;
-       dm->numFaceData = numFaces;
+       dm->numTessFaceData = numTessFaces;
+       dm->numLoopData = numLoops;
+       dm->numPolyData = numPolys;
 
        DM_init_funcs(dm);
        
        dm->needsFree = 1;
 
        DM_init_funcs(dm);
        
        dm->needsFree = 1;
+       dm->auto_bump_scale = -1.0f;
 }
 
 void DM_from_template(DerivedMesh *dm, DerivedMesh *source, DerivedMeshType type,
 }
 
 void DM_from_template(DerivedMesh *dm, DerivedMesh *source, DerivedMeshType type,
-                                         int numVerts, int numEdges, int numFaces)
+                      int numVerts, int numEdges, int numTessFaces,
+                      int numLoops, int numPolys)
 {
        CustomData_copy(&source->vertData, &dm->vertData, CD_MASK_DERIVEDMESH,
                                        CD_CALLOC, numVerts);
        CustomData_copy(&source->edgeData, &dm->edgeData, CD_MASK_DERIVEDMESH,
                                        CD_CALLOC, numEdges);
        CustomData_copy(&source->faceData, &dm->faceData, CD_MASK_DERIVEDMESH,
 {
        CustomData_copy(&source->vertData, &dm->vertData, CD_MASK_DERIVEDMESH,
                                        CD_CALLOC, numVerts);
        CustomData_copy(&source->edgeData, &dm->edgeData, CD_MASK_DERIVEDMESH,
                                        CD_CALLOC, numEdges);
        CustomData_copy(&source->faceData, &dm->faceData, CD_MASK_DERIVEDMESH,
-                                       CD_CALLOC, numFaces);
+                                       CD_CALLOC, numTessFaces);
+       CustomData_copy(&source->loopData, &dm->loopData, CD_MASK_DERIVEDMESH,
+                       CD_CALLOC, numLoops);
+       CustomData_copy(&source->polyData, &dm->polyData, CD_MASK_DERIVEDMESH,
+                       CD_CALLOC, numPolys);
 
        dm->type = type;
        dm->numVertData = numVerts;
        dm->numEdgeData = numEdges;
 
        dm->type = type;
        dm->numVertData = numVerts;
        dm->numEdgeData = numEdges;
-       dm->numFaceData = numFaces;
+       dm->numTessFaceData = numTessFaces;
+       dm->numLoopData = numLoops;
+       dm->numPolyData = numPolys;
 
        DM_init_funcs(dm);
 
 
        DM_init_funcs(dm);
 
@@ -213,63 +313,157 @@ int DM_release(DerivedMesh *dm)
                GPU_drawobject_free( dm );
                CustomData_free(&dm->vertData, dm->numVertData);
                CustomData_free(&dm->edgeData, dm->numEdgeData);
                GPU_drawobject_free( dm );
                CustomData_free(&dm->vertData, dm->numVertData);
                CustomData_free(&dm->edgeData, dm->numEdgeData);
-               CustomData_free(&dm->faceData, dm->numFaceData);
+               CustomData_free(&dm->faceData, dm->numTessFaceData);
+               CustomData_free(&dm->loopData, dm->numLoopData);
+               CustomData_free(&dm->polyData, dm->numPolyData);
 
                return 1;
        }
        else {
                CustomData_free_temporary(&dm->vertData, dm->numVertData);
                CustomData_free_temporary(&dm->edgeData, dm->numEdgeData);
 
                return 1;
        }
        else {
                CustomData_free_temporary(&dm->vertData, dm->numVertData);
                CustomData_free_temporary(&dm->edgeData, dm->numEdgeData);
-               CustomData_free_temporary(&dm->faceData, dm->numFaceData);
+               CustomData_free_temporary(&dm->faceData, dm->numTessFaceData);
+               CustomData_free_temporary(&dm->loopData, dm->numLoopData);
+               CustomData_free_temporary(&dm->polyData, dm->numPolyData);
 
                return 0;
        }
 }
 
 
                return 0;
        }
 }
 
-void DM_to_mesh(DerivedMesh *dm, Mesh *me)
+void DM_DupPolys(DerivedMesh *source, DerivedMesh *target)
+{
+       CustomData_free(&target->loopData, source->numLoopData);
+       CustomData_free(&target->polyData, source->numPolyData);
+
+       CustomData_copy(&source->loopData, &target->loopData, CD_MASK_DERIVEDMESH, CD_DUPLICATE, source->numLoopData);
+       CustomData_copy(&source->polyData, &target->polyData, CD_MASK_DERIVEDMESH, CD_DUPLICATE, source->numPolyData);
+
+       target->numLoopData = source->numLoopData;
+       target->numPolyData = source->numPolyData;
+
+       if (!CustomData_has_layer(&target->polyData, CD_MPOLY)) {
+               MPoly *mpoly;
+               MLoop *mloop;
+
+               mloop = source->dupLoopArray(source);
+               mpoly = source->dupPolyArray(source);
+               CustomData_add_layer(&target->loopData, CD_MLOOP, CD_ASSIGN, mloop, source->numLoopData);
+               CustomData_add_layer(&target->polyData, CD_MPOLY, CD_ASSIGN, mpoly, source->numPolyData);
+       }
+}
+
+/* note: until all modifiers can take MPoly's as input,
+ * use this at the start of modifiers  */
+void DM_ensure_tessface(DerivedMesh *dm)
+{
+       const int numTessFaces = dm->getNumTessFaces(dm);
+       const int numPolys =     dm->getNumPolys(dm);
+
+       if ( (numTessFaces == 0) && (numPolys != 0)) {
+               dm->recalcTesselation(dm);
+
+               if (dm->getNumTessFaces(dm)) {
+                       printf("warning %s: could not create tessfaces from %d polygons, dm->type=%d\n",
+                              __func__, numPolys, dm->type);
+               }
+               else {
+                       printf("info %s: polys -> ngons calculated\n", __func__);
+               }
+       }
+}
+
+void DM_to_mesh(DerivedMesh *dm, Mesh *me, Object *ob)
 {
        /* dm might depend on me, so we need to do everything with a local copy */
        Mesh tmp = *me;
 {
        /* dm might depend on me, so we need to do everything with a local copy */
        Mesh tmp = *me;
-       int totvert, totedge, totface;
-
+       int totvert, totedge /*, totface */ /* UNUSED */, totloop, totpoly;
+       int did_shapekeys=0;
+       
        memset(&tmp.vdata, 0, sizeof(tmp.vdata));
        memset(&tmp.edata, 0, sizeof(tmp.edata));
        memset(&tmp.fdata, 0, sizeof(tmp.fdata));
        memset(&tmp.vdata, 0, sizeof(tmp.vdata));
        memset(&tmp.edata, 0, sizeof(tmp.edata));
        memset(&tmp.fdata, 0, sizeof(tmp.fdata));
+       memset(&tmp.ldata, 0, sizeof(tmp.ldata));
+       memset(&tmp.pdata, 0, sizeof(tmp.pdata));
 
        totvert = tmp.totvert = dm->getNumVerts(dm);
        totedge = tmp.totedge = dm->getNumEdges(dm);
 
        totvert = tmp.totvert = dm->getNumVerts(dm);
        totedge = tmp.totedge = dm->getNumEdges(dm);
-       totface = tmp.totface = dm->getNumFaces(dm);
+       totloop = tmp.totloop = dm->getNumLoops(dm);
+       totpoly = tmp.totpoly = dm->getNumPolys(dm);
 
        CustomData_copy(&dm->vertData, &tmp.vdata, CD_MASK_MESH, CD_DUPLICATE, totvert);
        CustomData_copy(&dm->edgeData, &tmp.edata, CD_MASK_MESH, CD_DUPLICATE, totedge);
 
        CustomData_copy(&dm->vertData, &tmp.vdata, CD_MASK_MESH, CD_DUPLICATE, totvert);
        CustomData_copy(&dm->edgeData, &tmp.edata, CD_MASK_MESH, CD_DUPLICATE, totedge);
-       CustomData_copy(&dm->faceData, &tmp.fdata, CD_MASK_MESH, CD_DUPLICATE, totface);
+       CustomData_copy(&dm->loopData, &tmp.ldata, CD_MASK_MESH, CD_DUPLICATE, totloop);
+       CustomData_copy(&dm->polyData, &tmp.pdata, CD_MASK_MESH, CD_DUPLICATE, totpoly);
 
 
+       if (CustomData_has_layer(&dm->vertData, CD_SHAPEKEY)) {
+               KeyBlock *kb;
+               int i=0;
+               
+               if (ob) {
+                       for (kb=me->key->block.first; kb; kb=kb->next, i++) {
+                               if (i == ob->shapenr-1) {
+                                       i = kb->uid;
+                                       break;
+                               }
+                       }
+                       
+                       if (!kb) {
+                               printf("%s: error - could not find active shapekey %d!\n",
+                                      __func__, ob->shapenr-1);
+
+                               i = INT_MAX;
+                       }
+               } else {
+                       /*if no object, set to INT_MAX so we don't mess up any shapekey layers*/
+                       i = INT_MAX;
+               }
+               
+               shapekey_layers_to_keyblocks(dm, me, i);
+               did_shapekeys = 1;
+       }
+       
        /* not all DerivedMeshes store their verts/edges/faces in CustomData, so
           we set them here in case they are missing */
        if(!CustomData_has_layer(&tmp.vdata, CD_MVERT))
                CustomData_add_layer(&tmp.vdata, CD_MVERT, CD_ASSIGN, dm->dupVertArray(dm), totvert);
        if(!CustomData_has_layer(&tmp.edata, CD_MEDGE))
                CustomData_add_layer(&tmp.edata, CD_MEDGE, CD_ASSIGN, dm->dupEdgeArray(dm), totedge);
        /* not all DerivedMeshes store their verts/edges/faces in CustomData, so
           we set them here in case they are missing */
        if(!CustomData_has_layer(&tmp.vdata, CD_MVERT))
                CustomData_add_layer(&tmp.vdata, CD_MVERT, CD_ASSIGN, dm->dupVertArray(dm), totvert);
        if(!CustomData_has_layer(&tmp.edata, CD_MEDGE))
                CustomData_add_layer(&tmp.edata, CD_MEDGE, CD_ASSIGN, dm->dupEdgeArray(dm), totedge);
-       if(!CustomData_has_layer(&tmp.fdata, CD_MFACE))
-               CustomData_add_layer(&tmp.fdata, CD_MFACE, CD_ASSIGN, dm->dupFaceArray(dm), totface);
+       if(!CustomData_has_layer(&tmp.pdata, CD_MPOLY)) {
+               tmp.mloop = dm->dupLoopArray(dm);
+               tmp.mpoly = dm->dupPolyArray(dm);
+
+               CustomData_add_layer(&tmp.ldata, CD_MLOOP, CD_ASSIGN, tmp.mloop, tmp.totloop);
+               CustomData_add_layer(&tmp.pdata, CD_MPOLY, CD_ASSIGN, tmp.mpoly, tmp.totpoly);
+       }
 
        /* object had got displacement layer, should copy this layer to save sculpted data */
        /* NOTE: maybe some other layers should be copied? nazgul */
 
        /* object had got displacement layer, should copy this layer to save sculpted data */
        /* NOTE: maybe some other layers should be copied? nazgul */
-       if(CustomData_has_layer(&me->fdata, CD_MDISPS)) {
-               if (totface == me->totface) {
-                       MDisps *mdisps = CustomData_get_layer(&me->fdata, CD_MDISPS);
-                       CustomData_add_layer(&tmp.fdata, CD_MDISPS, CD_DUPLICATE, mdisps, totface);
+       if(CustomData_has_layer(&me->ldata, CD_MDISPS)) {
+               if (totloop == me->totloop) {
+                       MDisps *mdisps = CustomData_get_layer(&me->ldata, CD_MDISPS);
+                       CustomData_add_layer(&tmp.ldata, CD_MDISPS, CD_DUPLICATE, mdisps, totloop);
                }
        }
 
                }
        }
 
-       mesh_update_customdata_pointers(&tmp);
+       /* yes, must be before _and_ after tesselate */
+       mesh_update_customdata_pointers(&tmp, TRUE);
+
+       tmp.totface = mesh_recalcTesselation(&tmp.fdata, &tmp.ldata, &tmp.pdata, tmp.mvert, tmp.totface, tmp.totloop, tmp.totpoly);
+
+       mesh_update_customdata_pointers(&tmp, TRUE);
+
 
        CustomData_free(&me->vdata, me->totvert);
        CustomData_free(&me->edata, me->totedge);
        CustomData_free(&me->fdata, me->totface);
 
        CustomData_free(&me->vdata, me->totvert);
        CustomData_free(&me->edata, me->totedge);
        CustomData_free(&me->fdata, me->totface);
-
-       /* if the number of verts has changed, remove invalid data */
-       if(tmp.totvert != me->totvert) {
+       CustomData_free(&me->ldata, me->totloop);
+       CustomData_free(&me->pdata, me->totpoly);
+
+       /*  ok, this should now use new CD shapekey data,
+           which shouuld be fed through the modifier 
+               stack*/
+       if(tmp.totvert != me->totvert && !did_shapekeys && me->key) {
+               printf("YEEK! this should be recoded! Shape key loss!!!\n");
                if(tmp.key) tmp.key->id.us--;
                tmp.key = NULL;
        }
                if(tmp.key) tmp.key->id.us--;
                tmp.key = NULL;
        }
@@ -314,9 +508,19 @@ void DM_add_edge_layer(DerivedMesh *dm, int type, int alloctype, void *layer)
        CustomData_add_layer(&dm->edgeData, type, alloctype, layer, dm->numEdgeData);
 }
 
        CustomData_add_layer(&dm->edgeData, type, alloctype, layer, dm->numEdgeData);
 }
 
-void DM_add_face_layer(DerivedMesh *dm, int type, int alloctype, void *layer)
+void DM_add_tessface_layer(DerivedMesh *dm, int type, int alloctype, void *layer)
 {
 {
-       CustomData_add_layer(&dm->faceData, type, alloctype, layer, dm->numFaceData);
+       CustomData_add_layer(&dm->faceData, type, alloctype, layer, dm->numTessFaceData);
+}
+
+void DM_add_loop_layer(DerivedMesh *dm, int type, int alloctype, void *layer)
+{
+       CustomData_add_layer(&dm->loopData, type, alloctype, layer, dm->numLoopData);
+}
+
+void DM_add_poly_layer(DerivedMesh *dm, int type, int alloctype, void *layer)
+{
+       CustomData_add_layer(&dm->polyData, type, alloctype, layer, dm->numPolyData);
 }
 
 void *DM_get_vert_data(DerivedMesh *dm, int index, int type)
 }
 
 void *DM_get_vert_data(DerivedMesh *dm, int index, int type)
@@ -329,7 +533,7 @@ void *DM_get_edge_data(DerivedMesh *dm, int index, int type)
        return CustomData_get(&dm->edgeData, index, type);
 }
 
        return CustomData_get(&dm->edgeData, index, type);
 }
 
-void *DM_get_face_data(DerivedMesh *dm, int index, int type)
+void *DM_get_tessface_data(DerivedMesh *dm, int index, int type)
 {
        return CustomData_get(&dm->faceData, index, type);
 }
 {
        return CustomData_get(&dm->faceData, index, type);
 }
@@ -350,14 +554,19 @@ void *DM_get_edge_data_layer(DerivedMesh *dm, int type)
        return CustomData_get_layer(&dm->edgeData, type);
 }
 
        return CustomData_get_layer(&dm->edgeData, type);
 }
 
-void *DM_get_face_data_layer(DerivedMesh *dm, int type)
+void *DM_get_tessface_data_layer(DerivedMesh *dm, int type)
 {
 {
-       if(type == CD_MFACE)
-               return dm->getFaceArray(dm);
+       if (type == CD_MFACE)
+               return dm->getTessFaceArray(dm);
 
        return CustomData_get_layer(&dm->faceData, type);
 }
 
 
        return CustomData_get_layer(&dm->faceData, type);
 }
 
+void *DM_get_poly_data_layer(DerivedMesh *dm, int type)
+{
+       return CustomData_get_layer(&dm->polyData, type);
+}
+
 void DM_set_vert_data(DerivedMesh *dm, int index, int type, void *data)
 {
        CustomData_set(&dm->vertData, index, type, data);
 void DM_set_vert_data(DerivedMesh *dm, int index, int type, void *data)
 {
        CustomData_set(&dm->vertData, index, type, data);
@@ -368,7 +577,7 @@ void DM_set_edge_data(DerivedMesh *dm, int index, int type, void *data)
        CustomData_set(&dm->edgeData, index, type, data);
 }
 
        CustomData_set(&dm->edgeData, index, type, data);
 }
 
-void DM_set_face_data(DerivedMesh *dm, int index, int type, void *data)
+void DM_set_tessface_data(DerivedMesh *dm, int index, int type, void *data)
 {
        CustomData_set(&dm->faceData, index, type, data);
 }
 {
        CustomData_set(&dm->faceData, index, type, data);
 }
@@ -387,13 +596,27 @@ void DM_copy_edge_data(DerivedMesh *source, DerivedMesh *dest,
                                                 source_index, dest_index, count);
 }
 
                                                 source_index, dest_index, count);
 }
 
-void DM_copy_face_data(DerivedMesh *source, DerivedMesh *dest,
+void DM_copy_tessface_data(DerivedMesh *source, DerivedMesh *dest,
                                           int source_index, int dest_index, int count)
 {
        CustomData_copy_data(&source->faceData, &dest->faceData,
                                                 source_index, dest_index, count);
 }
 
                                           int source_index, int dest_index, int count)
 {
        CustomData_copy_data(&source->faceData, &dest->faceData,
                                                 source_index, dest_index, count);
 }
 
+void DM_copy_loop_data(DerivedMesh *source, DerivedMesh *dest,
+                       int source_index, int dest_index, int count)
+{
+       CustomData_copy_data(&source->loopData, &dest->loopData,
+                            source_index, dest_index, count);
+}
+
+void DM_copy_poly_data(DerivedMesh *source, DerivedMesh *dest,
+                       int source_index, int dest_index, int count)
+{
+       CustomData_copy_data(&source->polyData, &dest->polyData,
+                            source_index, dest_index, count);
+}
+
 void DM_free_vert_data(struct DerivedMesh *dm, int index, int count)
 {
        CustomData_free_elem(&dm->vertData, index, count);
 void DM_free_vert_data(struct DerivedMesh *dm, int index, int count)
 {
        CustomData_free_elem(&dm->vertData, index, count);
@@ -404,11 +627,21 @@ void DM_free_edge_data(struct DerivedMesh *dm, int index, int count)
        CustomData_free_elem(&dm->edgeData, index, count);
 }
 
        CustomData_free_elem(&dm->edgeData, index, count);
 }
 
-void DM_free_face_data(struct DerivedMesh *dm, int index, int count)
+void DM_free_tessface_data(struct DerivedMesh *dm, int index, int count)
 {
        CustomData_free_elem(&dm->faceData, index, count);
 }
 
 {
        CustomData_free_elem(&dm->faceData, index, count);
 }
 
+void DM_free_loop_data(struct DerivedMesh *dm, int index, int count)
+{
+       CustomData_free_elem(&dm->loopData, index, count);
+}
+
+void DM_free_poly_data(struct DerivedMesh *dm, int index, int count)
+{
+       CustomData_free_elem(&dm->polyData, index, count);
+}
+
 void DM_interp_vert_data(DerivedMesh *source, DerivedMesh *dest,
                                                 int *src_indices, float *weights,
                                                 int count, int dest_index)
 void DM_interp_vert_data(DerivedMesh *source, DerivedMesh *dest,
                                                 int *src_indices, float *weights,
                                                 int count, int dest_index)
@@ -426,7 +659,7 @@ void DM_interp_edge_data(DerivedMesh *source, DerivedMesh *dest,
                                          weights, (float*)vert_weights, count, dest_index);
 }
 
                                          weights, (float*)vert_weights, count, dest_index);
 }
 
-void DM_interp_face_data(DerivedMesh *source, DerivedMesh *dest,
+void DM_interp_tessface_data(DerivedMesh *source, DerivedMesh *dest,
                                                 int *src_indices,
                                                 float *weights, FaceVertWeight *vert_weights,
                                                 int count, int dest_index)
                                                 int *src_indices,
                                                 float *weights, FaceVertWeight *vert_weights,
                                                 int count, int dest_index)
@@ -435,13 +668,28 @@ void DM_interp_face_data(DerivedMesh *source, DerivedMesh *dest,
                                          weights, (float*)vert_weights, count, dest_index);
 }
 
                                          weights, (float*)vert_weights, count, dest_index);
 }
 
-void DM_swap_face_data(DerivedMesh *dm, int index, const int *corner_indices)
+void DM_swap_tessface_data(DerivedMesh *dm, int index, const int *corner_indices)
 {
        CustomData_swap(&dm->faceData, index, corner_indices);
 }
 
 {
        CustomData_swap(&dm->faceData, index, corner_indices);
 }
 
-///
+void DM_interp_loop_data(DerivedMesh *source, DerivedMesh *dest,
+                         int *src_indices,
+                         float *weights, int count, int dest_index)
+{
+       CustomData_interp(&source->loopData, &dest->loopData, src_indices,
+                         weights, NULL, count, dest_index);
+}
 
 
+void DM_interp_poly_data(DerivedMesh *source, DerivedMesh *dest,
+                         int *src_indices,
+                         float *weights, int count, int dest_index)
+{
+       CustomData_interp(&source->polyData, &dest->polyData, src_indices,
+                         weights, NULL, count, dest_index);
+}
+
+///
 DerivedMesh *mesh_create_derived(Mesh *me, Object *ob, float (*vertCos)[3])
 {
        DerivedMesh *dm = CDDM_from_mesh(me, ob);
 DerivedMesh *mesh_create_derived(Mesh *me, Object *ob, float (*vertCos)[3])
 {
        DerivedMesh *dm = CDDM_from_mesh(me, ob);
@@ -457,7 +705,10 @@ DerivedMesh *mesh_create_derived(Mesh *me, Object *ob, float (*vertCos)[3])
        return dm;
 }
 
        return dm;
 }
 
-DerivedMesh *mesh_create_derived_for_modifier(Scene *scene, Object *ob, ModifierData *md)
+/***/
+
+DerivedMesh *mesh_create_derived_for_modifier(Scene *scene, Object *ob, 
+       ModifierData *md, int build_shapekey_layers)
 {
        Mesh *me = ob->data;
        ModifierTypeInfo *mti = modifierType_getInfo(md->type);
 {
        Mesh *me = ob->data;
        ModifierTypeInfo *mti = modifierType_getInfo(md->type);
@@ -467,7 +718,11 @@ DerivedMesh *mesh_create_derived_for_modifier(Scene *scene, Object *ob, Modifier
        
        if (!(md->mode&eModifierMode_Realtime)) return NULL;
        if (mti->isDisabled && mti->isDisabled(md, 0)) return NULL;
        
        if (!(md->mode&eModifierMode_Realtime)) return NULL;
        if (mti->isDisabled && mti->isDisabled(md, 0)) return NULL;
-
+       
+       if (build_shapekey_layers && me->key && ob->shapenr <= BLI_countlist(&me->key->block)) {
+               key_to_mesh(BLI_findlink(&me->key->block, ob->shapenr-1), me);
+       }
+       
        if (mti->type==eModifierTypeType_OnlyDeform) {
                int numVerts;
                float (*deformedVerts)[3] = mesh_getVertexCos(me, &numVerts);
        if (mti->type==eModifierTypeType_OnlyDeform) {
                int numVerts;
                float (*deformedVerts)[3] = mesh_getVertexCos(me, &numVerts);
@@ -475,9 +730,16 @@ DerivedMesh *mesh_create_derived_for_modifier(Scene *scene, Object *ob, Modifier
                mti->deformVerts(md, ob, NULL, deformedVerts, numVerts, 0, 0);
                dm = mesh_create_derived(me, ob, deformedVerts);
 
                mti->deformVerts(md, ob, NULL, deformedVerts, numVerts, 0, 0);
                dm = mesh_create_derived(me, ob, deformedVerts);
 
+               if (build_shapekey_layers)
+                       add_shapekey_layers(dm, me, ob);
+               
                MEM_freeN(deformedVerts);
        } else {
                DerivedMesh *tdm = mesh_create_derived(me, ob, NULL);
                MEM_freeN(deformedVerts);
        } else {
                DerivedMesh *tdm = mesh_create_derived(me, ob, NULL);
+
+               if (build_shapekey_layers)
+                       add_shapekey_layers(tdm, me, ob);
+               
                dm = mti->applyModifier(md, ob, tdm, 0, 0);
 
                if(tdm != dm) tdm->release(tdm);
                dm = mti->applyModifier(md, ob, tdm, 0, 0);
 
                if(tdm != dm) tdm->release(tdm);
@@ -486,22 +748,22 @@ DerivedMesh *mesh_create_derived_for_modifier(Scene *scene, Object *ob, Modifier
        return dm;
 }
 
        return dm;
 }
 
-static float *get_editmesh_orco_verts(EditMesh *em)
+static float *get_editbmesh_orco_verts(BMEditMesh *em)
 {
 {
-       EditVert *eve;
+       BMIter iter;
+       BMVert *eve;
        float *orco;
        int a, totvert;
 
        /* these may not really be the orco's, but it's only for preview.
         * could be solver better once, but isn't simple */
 
        float *orco;
        int a, totvert;
 
        /* these may not really be the orco's, but it's only for preview.
         * could be solver better once, but isn't simple */
 
-       totvert= 0;
-       for(eve=em->verts.first; eve; eve=eve->next)
-               totvert++;
+       totvert= em->bm->totvert;
        
        orco = MEM_mallocN(sizeof(float)*3*totvert, "EditMesh Orco");
 
        
        orco = MEM_mallocN(sizeof(float)*3*totvert, "EditMesh Orco");
 
-       for(a=0, eve=em->verts.first; eve; eve=eve->next, a+=3) {
+       eve = BMIter_New(&iter, em->bm, BM_VERTS_OF_MESH, NULL);
+       for (a=0; eve; eve=BMIter_Step(&iter), a+=3) {
                copy_v3_v3(orco+a, eve->co);
        }
        
                copy_v3_v3(orco+a, eve->co);
        }
        
@@ -509,8 +771,7 @@ static float *get_editmesh_orco_verts(EditMesh *em)
 }
 
 /* orco custom data layer */
 }
 
 /* orco custom data layer */
-
-static void *get_orco_coords_dm(Object *ob, EditMesh *em, int layer, int *free)
+static void *get_orco_coords_dm(Object *ob, BMEditMesh *em, int layer, int *free)
 {
        *free= 0;
 
 {
        *free= 0;
 
@@ -519,7 +780,7 @@ static void *get_orco_coords_dm(Object *ob, EditMesh *em, int layer, int *free)
                *free= 1;
 
                if(em)
                *free= 1;
 
                if(em)
-                       return (float(*)[3])get_editmesh_orco_verts(em);
+                       return (float(*)[3])get_editbmesh_orco_verts(em);
                else
                        return (float(*)[3])get_mesh_orco_verts(ob);
        }
                else
                        return (float(*)[3])get_mesh_orco_verts(ob);
        }
@@ -540,13 +801,13 @@ static void *get_orco_coords_dm(Object *ob, EditMesh *em, int layer, int *free)
        return NULL;
 }
 
        return NULL;
 }
 
-static DerivedMesh *create_orco_dm(Object *ob, Mesh *me, EditMesh *em, int layer)
+static DerivedMesh *create_orco_dm(Object *ob, Mesh *me, BMEditMesh *em, int layer)
 {
        DerivedMesh *dm;
        float (*orco)[3];
        int free;
 
 {
        DerivedMesh *dm;
        float (*orco)[3];
        int free;
 
-       if(em) dm= CDDM_from_editmesh(em, me);
+       if(em) dm= CDDM_from_BMEditMesh(em, me, FALSE, FALSE);
        else dm= CDDM_from_mesh(me, ob);
 
        orco= get_orco_coords_dm(ob, em, layer, &free);
        else dm= CDDM_from_mesh(me, ob);
 
        orco= get_orco_coords_dm(ob, em, layer, &free);
@@ -561,7 +822,8 @@ static DerivedMesh *create_orco_dm(Object *ob, Mesh *me, EditMesh *em, int layer
        return dm;
 }
 
        return dm;
 }
 
-static void add_orco_dm(Object *ob, EditMesh *em, DerivedMesh *dm, DerivedMesh *orcodm, int layer)
+static void add_orco_dm(Object *ob, BMEditMesh *em, DerivedMesh *dm,
+                                               DerivedMesh *orcodm, int layer)
 {
        float (*orco)[3], (*layerorco)[3];
        int totvert, free;
 {
        float (*orco)[3], (*layerorco)[3];
        int totvert, free;
@@ -641,24 +903,40 @@ enum {
        CALC_WP_AUTO_NORMALIZE= (1<<1)
 };
 
        CALC_WP_AUTO_NORMALIZE= (1<<1)
 };
 
-static void calc_weightpaint_vert_color(Object *ob, ColorBand *coba, int vert, unsigned char *col, char *dg_flags, int selected, int UNUSED(unselected), const int draw_flag)
+static void weightpaint_color(unsigned char r_col[4], ColorBand *coba, const float input)
+{
+       float colf[4];
+
+       if(coba) do_colorband(coba, input, colf);
+       else     weight_to_rgb(colf, input);
+
+       r_col[3] = (unsigned char)(colf[0] * 255.0f);
+       r_col[2] = (unsigned char)(colf[1] * 255.0f);
+       r_col[1] = (unsigned char)(colf[2] * 255.0f);
+       r_col[0] = 255;
+}
+
+
+static void calc_weightpaint_vert_color(
+        unsigned char r_col[4],
+        MDeformVert *dv, ColorBand *coba,
+        const int defbase_tot, const int defbase_act,
+        const char *dg_flags,
+        const int selected, const int draw_flag)
 {
 {
-       Mesh *me = ob->data;
        float input = 0.0f;
        
        int make_black= FALSE;
 
        float input = 0.0f;
        
        int make_black= FALSE;
 
-       if (me->dvert) {
-               MDeformVert *dvert= &me->dvert[vert];
+       if ((selected > 1) && (draw_flag & CALC_WP_MULTIPAINT)) {
+               int was_a_nonzero= FALSE;
+               unsigned int i;
 
 
-               if ((selected > 1) && (draw_flag & CALC_WP_MULTIPAINT)) {
-                       int was_a_nonzero= FALSE;
-                       int i;
-
-                       MDeformWeight *dw= dvert->dw;
-                       for (i = dvert->totweight; i > 0; i--, dw++) {
-                               /* in multipaint, get the average if auto normalize is inactive
-                                * get the sum if it is active */
+               MDeformWeight *dw= dv->dw;
+               for (i = dv->totweight; i != 0; i--, dw++) {
+                       /* in multipaint, get the average if auto normalize is inactive
+                        * get the sum if it is active */
+                       if (dw->def_nr < defbase_tot) {
                                if (dg_flags[dw->def_nr]) {
                                        if (dw->weight) {
                                                input += dw->weight;
                                if (dg_flags[dw->def_nr]) {
                                        if (dw->weight) {
                                                input += dw->weight;
@@ -666,42 +944,30 @@ static void calc_weightpaint_vert_color(Object *ob, ColorBand *coba, int vert, u
                                        }
                                }
                        }
                                        }
                                }
                        }
+               }
 
 
-                       /* make it black if the selected groups have no weight on a vertex */
-                       if (was_a_nonzero == FALSE) {
-                               make_black = TRUE;
-                       }
-                       else if ((draw_flag & CALC_WP_AUTO_NORMALIZE) == FALSE) {
-                               input /= selected; /* get the average */
-                       }
+               /* make it black if the selected groups have no weight on a vertex */
+               if (was_a_nonzero == FALSE) {
+                       make_black = TRUE;
                }
                }
-               else {
-                       /* default, non tricky behavior */
-                       input= defvert_find_weight(dvert, ob->actdef-1);
+               else if ((draw_flag & CALC_WP_AUTO_NORMALIZE) == FALSE) {
+                       input /= selected; /* get the average */
                }
        }
                }
        }
-       
-       if (make_black) {
-               col[3] = 0;
-               col[2] = 0;
-               col[1] = 0;
-               col[0] = 255;
+       else {
+               /* default, non tricky behavior */
+               input= defvert_find_weight(dv, defbase_act);
+       }
+
+       if (make_black) { /* TODO, theme color */
+               r_col[3] = 0;
+               r_col[2] = 0;
+               r_col[1] = 0;
+               r_col[0] = 255;
        }
        else {
        }
        else {
-               float colf[4];
                CLAMP(input, 0.0f, 1.0f);
                CLAMP(input, 0.0f, 1.0f);
-
-               colf[0]= colf[1]= colf[2]= -1;
-
-               if(coba)
-                       do_colorband(coba, input, colf);
-               else
-                       weight_to_rgb(colf, input);
-
-               col[3] = (unsigned char)(colf[0] * 255.0f);
-               col[2] = (unsigned char)(colf[1] * 255.0f);
-               col[1] = (unsigned char)(colf[2] * 255.0f);
-               col[0] = 255;
+               weightpaint_color(r_col, coba, input);
        }
 }
 
        }
 }
 
@@ -712,33 +978,186 @@ void vDM_ColorBand_store(ColorBand *coba)
        stored_cb= coba;
 }
 
        stored_cb= coba;
 }
 
-static void add_weight_mcol_dm(Object *ob, DerivedMesh *dm, int const draw_flag)
+/* return an array of vertex weight colors, caller must free.
+ *
+ * note that we could save some memory and allocate RGB only but then we'd need to
+ * re-arrange the colors when copying to the face since MCol has odd ordering,
+ * so leave this as is - campbell */
+static unsigned char *calc_weightpaint_vert_array(Object *ob, int const draw_flag, ColorBand *coba)
 {
        Mesh *me = ob->data;
 {
        Mesh *me = ob->data;
-       MFace *mf = me->mface;
+       unsigned char *wtcol_v = MEM_mallocN (sizeof(unsigned char) * me->totvert * 4, "weightmap_v");
+
+       if (me->dvert) {
+               unsigned char *wc = wtcol_v;
+               MDeformVert *dv= me->dvert;
+               unsigned int i;
+
+               /* varisbles for multipaint */
+               const int defbase_tot = BLI_countlist(&ob->defbase);
+               const int defbase_act = ob->actdef-1;
+               char *dg_flags = MEM_mallocN(defbase_tot * sizeof(char), __func__);
+               const int selected = get_selected_defgroups(ob, dg_flags, defbase_tot);
+               /* const int unselected = defbase_tot - selected; */ /* UNUSED */
+
+               for (i = me->totvert; i != 0; i--, wc += 4, dv++) {
+                       calc_weightpaint_vert_color(wc, dv, coba, defbase_tot, defbase_act, dg_flags, selected, draw_flag);
+               }
+
+               MEM_freeN(dg_flags);
+       }
+       else {
+               int col_i;
+               weightpaint_color((unsigned char *)&col_i, coba, 0.0f);
+               fill_vn_i((int *)wtcol_v, me->totvert, col_i);
+       }
+
+       return wtcol_v;
+}
+
+static void add_weight_mcol_dm(Object *ob, DerivedMesh *dm, int const draw_flag)
+{
        ColorBand *coba= stored_cb;     /* warning, not a local var */
        ColorBand *coba= stored_cb;     /* warning, not a local var */
-       unsigned char *wtcol;
-       int i;
-       
-       int defbase_len = BLI_countlist(&ob->defbase);
-       char *defbase_sel = MEM_mallocN(defbase_len * sizeof(char), __func__);
-       int selected = get_selected_defgroups(ob, defbase_sel, defbase_len);
-       int unselected = defbase_len - selected;
+       unsigned char *wtcol_v = calc_weightpaint_vert_array(ob, draw_flag, coba);
+       unsigned char *wtcol_f;
+       unsigned char(*wtcol_l)[4] = NULL;
+       BLI_array_declare(wtcol_l);
+       MFace *mf = dm->getTessFaceArray(dm);
+       MLoop *mloop = dm->getLoopArray(dm), *ml;
+       MPoly *mp = dm->getPolyArray(dm);
+       int i, j, totface=dm->getNumTessFaces(dm), totloop;
+       int *origIndex = dm->getVertDataArray(dm, CD_ORIGINDEX);
+       unsigned char *wtcol_f_step;
+
+       wtcol_f = MEM_mallocN(sizeof (unsigned char) * totface*4*4, "weightmap_f");
+       wtcol_f_step = wtcol_f;
+
+       /*first add colors to the tesselation faces*/
+       for (i=0; i<totface; i++, mf++, wtcol_f_step += (4 * 4)) {
+               /*origindex being NULL means we're operating on original mesh data*/
+#if 0
+               unsigned int fidx= mf->v4 ? 3:2;
+
+#else  /* better zero out triangles 4th component. else valgrind complains when the buffer's copied */
+               unsigned int fidx;
+               if (mf->v4) {
+                       fidx = 3;
+               }
+               else {
+                       fidx = 2;
+                       *(int *)(&wtcol_f_step[3 * 4]) = 0;
+               }
+#endif
 
 
-       wtcol = MEM_callocN (sizeof (unsigned char) * me->totface*4*4, "weightmap");
+               do {
+                       copy_v4_v4_char((char *)&wtcol_f_step[fidx * 4],
+                                       (char *)&wtcol_v[4 * (*(&mf->v1 + fidx))]);
+               } while (fidx--);
+       }
+
+       CustomData_add_layer(&dm->faceData, CD_WEIGHT_MCOL, CD_ASSIGN, wtcol_f, totface);
+
+       /*now add to loops, so the data can be passed through the modifier stack*/
+       totloop = 0;
+       for (i=0; i<dm->numPolyData; i++, mp++) {
+               ml = mloop + mp->loopstart;
+
+               for (j=0; j<mp->totloop; j++, ml++, totloop++) {
+                       BLI_array_growone(wtcol_l);
+                       copy_v4_v4_char((char *)&wtcol_l[totloop],
+                                       (char *)&wtcol_v[4 * (origIndex ? origIndex[ml->v] : ml->v)]);
+               }
+       }
+
+       MEM_freeN(wtcol_v);
+
+       CustomData_add_layer(&dm->loopData, CD_WEIGHT_MLOOPCOL, CD_ASSIGN, wtcol_l, totloop);
+}
+
+
+static void shapekey_layers_to_keyblocks(DerivedMesh *dm, Mesh *me, int actshape_uid)
+{
+       KeyBlock *kb;
+       int i, j, tot;
+       
+       if (!me->key)
+               return; 
        
        
-       memset(wtcol, 0x55, sizeof (unsigned char) * me->totface*4*4);
-       for (i=0; i<me->totface; i++, mf++) {
-               calc_weightpaint_vert_color(ob, coba, mf->v1, &wtcol[(i*4 + 0)*4], defbase_sel, selected, unselected, draw_flag);
-               calc_weightpaint_vert_color(ob, coba, mf->v2, &wtcol[(i*4 + 1)*4], defbase_sel, selected, unselected, draw_flag);
-               calc_weightpaint_vert_color(ob, coba, mf->v3, &wtcol[(i*4 + 2)*4], defbase_sel, selected, unselected, draw_flag);
-               if (mf->v4)
-                       calc_weightpaint_vert_color(ob, coba, mf->v4, &wtcol[(i*4 + 3)*4], defbase_sel, selected, unselected, draw_flag);
+       tot = CustomData_number_of_layers(&dm->vertData, CD_SHAPEKEY);
+       for (i=0; i<tot; i++) {
+               CustomDataLayer *layer = &dm->vertData.layers[CustomData_get_layer_index_n(&dm->vertData, CD_SHAPEKEY, i)];
+               float (*cos)[3], (*kbcos)[3];
+               
+               for (kb=me->key->block.first; kb; kb=kb->next) {
+                       if (kb->uid == layer->uid)
+                               break;
+               }
+               
+               if (!kb) {
+                       kb = add_keyblock(me->key, layer->name);
+                       kb->uid = layer->uid;
+               }
+               
+               if (kb->data)
+                       MEM_freeN(kb->data);
+               
+               cos = CustomData_get_layer_n(&dm->vertData, CD_SHAPEKEY, i);
+               kb->totelem = dm->numVertData;
+
+               kb->data = kbcos = MEM_mallocN(sizeof(float)*3*kb->totelem, "kbcos DerivedMesh.c");
+               if (kb->uid == actshape_uid) {
+                       MVert *mvert = dm->getVertArray(dm);
+                       
+                       for (j=0; j<dm->numVertData; j++, kbcos++, mvert++) {
+                               copy_v3_v3(*kbcos, mvert->co);
+                       }
+               } else {
+                       for (j=0; j<kb->totelem; j++, cos++, kbcos++) {
+                               copy_v3_v3(*kbcos, *cos);
+                       }
+               }
        }
        
        }
        
-       MEM_freeN(defbase_sel);
+       for (kb=me->key->block.first; kb; kb=kb->next) {
+               if (kb->totelem != dm->numVertData) {
+                       if (kb->data)
+                               MEM_freeN(kb->data);
+                       
+                       kb->totelem = dm->numVertData;
+                       kb->data = MEM_callocN(sizeof(float)*3*kb->totelem, "kb->data derivedmesh.c");
+                       fprintf(stderr, "%s: lost a shapekey layer! (bmesh internal error)\n", __func__);
+               }
+       }
+}
 
 
-       CustomData_add_layer(&dm->faceData, CD_WEIGHT_MCOL, CD_ASSIGN, wtcol, dm->numFaceData);
+static void add_shapekey_layers(DerivedMesh *dm, Mesh *me, Object *UNUSED(ob))
+{
+       KeyBlock *kb;
+       Key *key = me->key;
+       int a, b;
+       
+       if (!me->key)
+               return;
+       
+       if (dm->numVertData != me->totvert) {
+               printf("error in add_shapekey_layers: dm isn't the same size as me\n");
+               return;
+       }
+               
+       for (a=0, kb=key->block.first; kb; kb=kb->next, a++) {
+               float (*cos)[3] = CustomData_add_layer_named(&dm->vertData, CD_SHAPEKEY, CD_CALLOC, NULL, dm->numVertData, kb->name);
+               int ci = CustomData_get_layer_index_n(&dm->vertData, CD_SHAPEKEY, a);
+               
+               dm->vertData.layers[ci].uid = kb->uid;
+               if (kb->totelem != dm->numVertData) {
+                       printf("error in add_shapekey_layers: totelem and totvert don't match");
+                       continue;
+               }
+               
+               for (b=0; b<kb->totelem; b++, cos++) {
+                       copy_v3_v3((float *)cos, ((float*)kb->data)+b*3);
+               }
+       }
 }
 
 /* new value for useDeform -1  (hack for the gameengine):
 }
 
 /* new value for useDeform -1  (hack for the gameengine):
@@ -749,14 +1168,15 @@ static void add_weight_mcol_dm(Object *ob, DerivedMesh *dm, int const draw_flag)
 static void mesh_calc_modifiers(Scene *scene, Object *ob, float (*inputVertexCos)[3],
                                                                DerivedMesh **deform_r, DerivedMesh **final_r,
                                                                int useRenderParams, int useDeform,
 static void mesh_calc_modifiers(Scene *scene, Object *ob, float (*inputVertexCos)[3],
                                                                DerivedMesh **deform_r, DerivedMesh **final_r,
                                                                int useRenderParams, int useDeform,
-                                                               int needMapping, CustomDataMask dataMask, int index, int useCache)
+                                                               int needMapping, CustomDataMask dataMask, 
+                                                               int index, int useCache, int build_shapekey_layers)
 {
        Mesh *me = ob->data;
        ModifierData *firstmd, *md;
        LinkNode *datamasks, *curr;
        CustomDataMask mask, nextmask, append_mask = 0;
        float (*deformedVerts)[3] = NULL;
 {
        Mesh *me = ob->data;
        ModifierData *firstmd, *md;
        LinkNode *datamasks, *curr;
        CustomDataMask mask, nextmask, append_mask = 0;
        float (*deformedVerts)[3] = NULL;
-       DerivedMesh *dm, *orcodm, *clothorcodm, *finaldm;
+       DerivedMesh *dm=NULL, *orcodm, *clothorcodm, *finaldm;
        int numVerts = me->totvert;
        int required_mode;
        int isPrevDeform= FALSE;
        int numVerts = me->totvert;
        int required_mode;
        int isPrevDeform= FALSE;
@@ -827,7 +1247,10 @@ static void mesh_calc_modifiers(Scene *scene, Object *ob, float (*inputVertexCos
                 */
                if (deform_r) {
                        *deform_r = CDDM_from_mesh(me, ob);
                 */
                if (deform_r) {
                        *deform_r = CDDM_from_mesh(me, ob);
-
+                        
+                       if (build_shapekey_layers)
+                               add_shapekey_layers(dm, me, ob);
+                       
                        if(deformedVerts) {
                                CDDM_apply_vert_coords(*deform_r, deformedVerts);
                                CDDM_calc_normals(*deform_r);
                        if(deformedVerts) {
                                CDDM_apply_vert_coords(*deform_r, deformedVerts);
                                CDDM_calc_normals(*deform_r);
@@ -931,7 +1354,7 @@ static void mesh_calc_modifiers(Scene *scene, Object *ob, float (*inputVertexCos
                        /* apply vertex coordinates or build a DerivedMesh as necessary */
                        if(dm) {
                                if(deformedVerts) {
                        /* apply vertex coordinates or build a DerivedMesh as necessary */
                        if(dm) {
                                if(deformedVerts) {
-                                       DerivedMesh *tdm = CDDM_copy(dm);
+                                       DerivedMesh *tdm = CDDM_copy(dm, 0);
                                        dm->release(dm);
                                        dm = tdm;
 
                                        dm->release(dm);
                                        dm = tdm;
 
@@ -941,14 +1364,14 @@ static void mesh_calc_modifiers(Scene *scene, Object *ob, float (*inputVertexCos
                        } else {
                                dm = CDDM_from_mesh(me, ob);
 
                        } else {
                                dm = CDDM_from_mesh(me, ob);
 
+                               if (build_shapekey_layers)
+                                       add_shapekey_layers(dm, me, ob);
+
                                if(deformedVerts) {
                                        CDDM_apply_vert_coords(dm, deformedVerts);
                                        CDDM_calc_normals(dm);
                                }
 
                                if(deformedVerts) {
                                        CDDM_apply_vert_coords(dm, deformedVerts);
                                        CDDM_calc_normals(dm);
                                }
 
-                               if((dataMask & CD_MASK_WEIGHT_MCOL) && (ob->mode & OB_MODE_WEIGHT_PAINT))
-                                       add_weight_mcol_dm(ob, dm, draw_flag); 
-
                                /* Constructive modifiers need to have an origindex
                                 * otherwise they wont have anywhere to copy the data from.
                                 *
                                /* Constructive modifiers need to have an origindex
                                 * otherwise they wont have anywhere to copy the data from.
                                 *
@@ -960,12 +1383,16 @@ static void mesh_calc_modifiers(Scene *scene, Object *ob, float (*inputVertexCos
                                        /* calc */
                                        DM_add_vert_layer(dm, CD_ORIGINDEX, CD_CALLOC, NULL);
                                        DM_add_edge_layer(dm, CD_ORIGINDEX, CD_CALLOC, NULL);
                                        /* calc */
                                        DM_add_vert_layer(dm, CD_ORIGINDEX, CD_CALLOC, NULL);
                                        DM_add_edge_layer(dm, CD_ORIGINDEX, CD_CALLOC, NULL);
-                                       DM_add_face_layer(dm, CD_ORIGINDEX, CD_CALLOC, NULL);
+                                       DM_add_poly_layer(dm, CD_ORIGINDEX, CD_CALLOC, NULL);
 
                                        range_vn_i(DM_get_vert_data_layer(dm, CD_ORIGINDEX), dm->numVertData, 0);
                                        range_vn_i(DM_get_edge_data_layer(dm, CD_ORIGINDEX), dm->numEdgeData, 0);
 
                                        range_vn_i(DM_get_vert_data_layer(dm, CD_ORIGINDEX), dm->numVertData, 0);
                                        range_vn_i(DM_get_edge_data_layer(dm, CD_ORIGINDEX), dm->numEdgeData, 0);
-                                       range_vn_i(DM_get_face_data_layer(dm, CD_ORIGINDEX), dm->numFaceData, 0);
+                                       range_vn_i(DM_get_poly_data_layer(dm, CD_ORIGINDEX), dm->numPolyData, 0);
                                }
                                }
+
+                               if((dataMask & CD_MASK_WEIGHT_MCOL) && (ob->mode & OB_MODE_WEIGHT_PAINT))
+                                       add_weight_mcol_dm(ob, dm, draw_flag);
+
                        }
 
                        
                        }
 
                        
@@ -983,7 +1410,7 @@ static void mesh_calc_modifiers(Scene *scene, Object *ob, float (*inputVertexCos
                        /* add an origspace layer if needed */
                        if(((CustomDataMask)GET_INT_FROM_POINTER(curr->link)) & CD_MASK_ORIGSPACE)
                                if(!CustomData_has_layer(&dm->faceData, CD_ORIGSPACE))
                        /* add an origspace layer if needed */
                        if(((CustomDataMask)GET_INT_FROM_POINTER(curr->link)) & CD_MASK_ORIGSPACE)
                                if(!CustomData_has_layer(&dm->faceData, CD_ORIGSPACE))
-                                       DM_add_face_layer(dm, CD_ORIGSPACE, CD_DEFAULT, NULL);
+                                       DM_add_tessface_layer(dm, CD_ORIGSPACE, CD_DEFAULT, NULL);
 
                        ndm = mti->applyModifier(md, ob, dm, useRenderParams, useCache);
 
 
                        ndm = mti->applyModifier(md, ob, dm, useRenderParams, useCache);
 
@@ -1056,7 +1483,7 @@ static void mesh_calc_modifiers(Scene *scene, Object *ob, float (*inputVertexCos
         * DerivedMesh then we need to build one.
         */
        if(dm && deformedVerts) {
         * DerivedMesh then we need to build one.
         */
        if(dm && deformedVerts) {
-               finaldm = CDDM_copy(dm);
+               finaldm = CDDM_copy(dm, 0);
 
                dm->release(dm);
 
 
                dm->release(dm);
 
@@ -1068,13 +1495,23 @@ static void mesh_calc_modifiers(Scene *scene, Object *ob, float (*inputVertexCos
        } else if(dm) {
                finaldm = dm;
        } else {
        } else if(dm) {
                finaldm = dm;
        } else {
-               finaldm = CDDM_from_mesh(me, ob);
+               int recalc_normals= 0;
 
 
+               finaldm = CDDM_from_mesh(me, ob);
+               
+               if(build_shapekey_layers) {
+                       add_shapekey_layers(finaldm, me, ob);
+                       recalc_normals= 1;
+               }
+               
                if(deformedVerts) {
                        CDDM_apply_vert_coords(finaldm, deformedVerts);
                if(deformedVerts) {
                        CDDM_apply_vert_coords(finaldm, deformedVerts);
-                       CDDM_calc_normals(finaldm);
+                       recalc_normals= 1;
                }
 
                }
 
+               if(recalc_normals)
+                       CDDM_calc_normals(finaldm);
+               
                if((dataMask & CD_MASK_WEIGHT_MCOL) && (ob->mode & OB_MODE_WEIGHT_PAINT))
                        add_weight_mcol_dm(ob, finaldm, draw_flag);
        }
                if((dataMask & CD_MASK_WEIGHT_MCOL) && (ob->mode & OB_MODE_WEIGHT_PAINT))
                        add_weight_mcol_dm(ob, finaldm, draw_flag);
        }
@@ -1099,6 +1536,23 @@ static void mesh_calc_modifiers(Scene *scene, Object *ob, float (*inputVertexCos
        }
 #endif /* WITH_GAMEENGINE */
 
        }
 #endif /* WITH_GAMEENGINE */
 
+
+       /* --------------------------------------------------------------------- */
+       /* Re-tesselation is necessary to push render data (uvs, textures, colors)
+        * from loops and polys onto the tessfaces. This may be currently be
+        * redundantin cases where the render mode doesn't use these inputs, but
+        * ideally eventually tesselation would happen on-demand, and this is one
+        * of the primary places it would be needed. */
+       finaldm->recalcTesselation(finaldm);
+       /* if we have no modifiers applied we'lll still want the tessface normals
+        * to be calculated from the polygon noramals,
+        * 'CDDM_calc_normals_mapping' checks for this case - campbell */
+       finaldm->calcNormals(finaldm);
+       /* Need to watch this, it can cause issues, see bug [#29338]             */
+       /* take care with this block, we really need testing frameworks          */
+       /* --------------------------------------------------------------------- */
+
+
        *final_r = finaldm;
 
        if(orcodm)
        *final_r = finaldm;
 
        if(orcodm)
@@ -1112,21 +1566,24 @@ static void mesh_calc_modifiers(Scene *scene, Object *ob, float (*inputVertexCos
        BLI_linklist_free(datamasks, NULL);
 }
 
        BLI_linklist_free(datamasks, NULL);
 }
 
-float (*editmesh_get_vertex_cos(EditMesh *em, int *numVerts_r))[3]
+float (*editbmesh_get_vertex_cos(BMEditMesh *em, int *numVerts_r))[3]
 {
 {
-       int i, numVerts = *numVerts_r = BLI_countlist(&em->verts);
+       int i, numVerts = *numVerts_r = em->bm->totvert;
        float (*cos)[3];
        float (*cos)[3];
-       EditVert *eve;
+       BMIter iter;
+       BMVert *eve;
+
+       cos = MEM_mallocN(sizeof(float)*3*numVerts, "vertexcos");
 
 
-       cos = MEM_mallocN(sizeof(*cos)*numVerts, "vertexcos");
-       for (i=0,eve=em->verts.first; i<numVerts; i++,eve=eve->next) {
+       eve = BMIter_New(&iter, em->bm, BM_VERTS_OF_MESH, NULL);
+       for (i=0; eve; eve=BMIter_Step(&iter), i++) {
                copy_v3_v3(cos[i], eve->co);
        }
 
        return cos;
 }
 
                copy_v3_v3(cos[i], eve->co);
        }
 
        return cos;
 }
 
-int editmesh_modifier_is_enabled(Scene *scene, ModifierData *md, DerivedMesh *dm)
+int editbmesh_modifier_is_enabled(Scene *scene, ModifierData *md, DerivedMesh *dm)
 {
        ModifierTypeInfo *mti = modifierType_getInfo(md->type);
        int required_mode = eModifierMode_Realtime | eModifierMode_Editmode;
 {
        ModifierTypeInfo *mti = modifierType_getInfo(md->type);
        int required_mode = eModifierMode_Realtime | eModifierMode_Editmode;
@@ -1140,7 +1597,7 @@ int editmesh_modifier_is_enabled(Scene *scene, ModifierData *md, DerivedMesh *dm
        return 1;
 }
 
        return 1;
 }
 
-static void editmesh_calc_modifiers(Scene *scene, Object *ob, EditMesh *em, DerivedMesh **cage_r,
+static void editbmesh_calc_modifiers(Scene *scene, Object *ob, BMEditMesh *em, DerivedMesh **cage_r,
                                                                        DerivedMesh **final_r,
                                                                        CustomDataMask dataMask)
 {
                                                                        DerivedMesh **final_r,
                                                                        CustomDataMask dataMask)
 {
@@ -1155,7 +1612,7 @@ static void editmesh_calc_modifiers(Scene *scene, Object *ob, EditMesh *em, Deri
        modifiers_clearErrors(ob);
 
        if(cage_r && cageIndex == -1) {
        modifiers_clearErrors(ob);
 
        if(cage_r && cageIndex == -1) {
-               *cage_r = editmesh_get_derived(em, NULL);
+               *cage_r = getEditDerivedBMesh(em, ob, NULL);
        }
 
        dm = NULL;
        }
 
        dm = NULL;
@@ -1169,7 +1626,7 @@ static void editmesh_calc_modifiers(Scene *scene, Object *ob, EditMesh *em, Deri
 
                md->scene= scene;
                
 
                md->scene= scene;
                
-               if(!editmesh_modifier_is_enabled(scene, md, dm))
+               if(!editbmesh_modifier_is_enabled(scene, md, dm))
                        continue;
 
                /* add an orco layer if needed by this modifier */
                        continue;
 
                /* add an orco layer if needed by this modifier */
@@ -1197,7 +1654,7 @@ static void editmesh_calc_modifiers(Scene *scene, Object *ob, EditMesh *em, Deri
                                                MEM_mallocN(sizeof(*deformedVerts) * numVerts, "dfmv");
                                        dm->getVertCos(dm, deformedVerts);
                                } else {
                                                MEM_mallocN(sizeof(*deformedVerts) * numVerts, "dfmv");
                                        dm->getVertCos(dm, deformedVerts);
                                } else {
-                                       deformedVerts = editmesh_get_vertex_cos(em, &numVerts);
+                                       deformedVerts = editbmesh_get_vertex_cos(em, &numVerts);
                                }
                        }
 
                                }
                        }
 
@@ -1210,7 +1667,7 @@ static void editmesh_calc_modifiers(Scene *scene, Object *ob, EditMesh *em, Deri
                        /* apply vertex coordinates or build a DerivedMesh as necessary */
                        if(dm) {
                                if(deformedVerts) {
                        /* apply vertex coordinates or build a DerivedMesh as necessary */
                        if(dm) {
                                if(deformedVerts) {
-                                       DerivedMesh *tdm = CDDM_copy(dm);
+                                       DerivedMesh *tdm = CDDM_copy(dm, 0);
                                        if(!(cage_r && dm == *cage_r)) dm->release(dm);
                                        dm = tdm;
 
                                        if(!(cage_r && dm == *cage_r)) dm->release(dm);
                                        dm = tdm;
 
@@ -1219,11 +1676,11 @@ static void editmesh_calc_modifiers(Scene *scene, Object *ob, EditMesh *em, Deri
                                } else if(cage_r && dm == *cage_r) {
                                        /* dm may be changed by this modifier, so we need to copy it
                                         */
                                } else if(cage_r && dm == *cage_r) {
                                        /* dm may be changed by this modifier, so we need to copy it
                                         */
-                                       dm = CDDM_copy(dm);
+                                       dm = CDDM_copy(dm, 0);
                                }
 
                        } else {
                                }
 
                        } else {
-                               dm = CDDM_from_editmesh(em, ob->data);
+                               dm = CDDM_from_BMEditMesh(em, ob->data, FALSE, FALSE);
 
                                if(deformedVerts) {
                                        CDDM_apply_vert_coords(dm, deformedVerts);
 
                                if(deformedVerts) {
                                        CDDM_apply_vert_coords(dm, deformedVerts);
@@ -1259,7 +1716,7 @@ static void editmesh_calc_modifiers(Scene *scene, Object *ob, EditMesh *em, Deri
 
                        if(mask & CD_MASK_ORIGSPACE)
                                if(!CustomData_has_layer(&dm->faceData, CD_ORIGSPACE))
 
                        if(mask & CD_MASK_ORIGSPACE)
                                if(!CustomData_has_layer(&dm->faceData, CD_ORIGSPACE))
-                                       DM_add_face_layer(dm, CD_ORIGSPACE, CD_DEFAULT, NULL);
+                                       DM_add_tessface_layer(dm, CD_ORIGSPACE, CD_DEFAULT, NULL);
                        
                        if (mti->applyModifierEM)
                                ndm = mti->applyModifierEM(md, ob, em, dm);
                        
                        if (mti->applyModifierEM)
                                ndm = mti->applyModifierEM(md, ob, em, dm);
@@ -1281,13 +1738,13 @@ static void editmesh_calc_modifiers(Scene *scene, Object *ob, EditMesh *em, Deri
 
                if(cage_r && i == cageIndex) {
                        if(dm && deformedVerts) {
 
                if(cage_r && i == cageIndex) {
                        if(dm && deformedVerts) {
-                               *cage_r = CDDM_copy(dm);
+                               *cage_r = CDDM_copy(dm, 0);
                                CDDM_apply_vert_coords(*cage_r, deformedVerts);
                        } else if(dm) {
                                *cage_r = dm;
                        } else {
                                *cage_r =
                                CDDM_apply_vert_coords(*cage_r, deformedVerts);
                        } else if(dm) {
                                *cage_r = dm;
                        } else {
                                *cage_r =
-                                       editmesh_get_derived(em,
+                                       getEditDerivedBMesh(em, ob,
                                                deformedVerts ? MEM_dupallocN(deformedVerts) : NULL);
                        }
                }
                                                deformedVerts ? MEM_dupallocN(deformedVerts) : NULL);
                        }
                }
@@ -1300,19 +1757,22 @@ static void editmesh_calc_modifiers(Scene *scene, Object *ob, EditMesh *em, Deri
         * then we need to build one.
         */
        if(dm && deformedVerts) {
         * then we need to build one.
         */
        if(dm && deformedVerts) {
-               *final_r = CDDM_copy(dm);
+               *final_r = CDDM_copy(dm, 0);
 
                if(!(cage_r && dm == *cage_r)) dm->release(dm);
 
                CDDM_apply_vert_coords(*final_r, deformedVerts);
 
                if(!(cage_r && dm == *cage_r)) dm->release(dm);
 
                CDDM_apply_vert_coords(*final_r, deformedVerts);
-               CDDM_calc_normals(*final_r);
+               CDDM_calc_normals_mapping(*final_r);
        } else if (dm) {
                *final_r = dm;
        } else if (dm) {
                *final_r = dm;
+               (*final_r)->calcNormals(*final_r); /* BMESH_ONLY - BMESH_TODO. check if this is needed */
        } else if (!deformedVerts && cage_r && *cage_r) {
                *final_r = *cage_r;
        } else if (!deformedVerts && cage_r && *cage_r) {
                *final_r = *cage_r;
+               (*final_r)->calcNormals(*final_r); /* BMESH_ONLY - BMESH_TODO. check if this is needed */
        } else {
        } else {
-               *final_r = editmesh_get_derived(em, deformedVerts);
+               *final_r = getEditDerivedBMesh(em, ob, deformedVerts);
                deformedVerts = NULL;
                deformedVerts = NULL;
+               (*final_r)->calcNormals(*final_r); /* BMESH_ONLY - BMESH_TODO. check if this is needed */
        }
 
        /* add an orco layer if needed */
        }
 
        /* add an orco layer if needed */
@@ -1358,18 +1818,19 @@ static void clear_mesh_caches(Object *ob)
        }
 }
 
        }
 }
 
-static void mesh_build_data(Scene *scene, Object *ob, CustomDataMask dataMask)
+static void mesh_build_data(Scene *scene, Object *ob, CustomDataMask dataMask,
+       int build_shapekey_layers)
 {
        Object *obact = scene->basact?scene->basact->object:NULL;
 {
        Object *obact = scene->basact?scene->basact->object:NULL;
-       int editing = paint_facesel_test(ob) || paint_vertsel_test(ob);/* paint_vertsel_test */
+       int editing = paint_facesel_test(ob);
        /* weight paint and face select need original indices because of selection buffer drawing */
        /* weight paint and face select need original indices because of selection buffer drawing */
-       int needMapping = (ob==obact) && (editing || (ob->mode & (OB_MODE_WEIGHT_PAINT|OB_MODE_VERTEX_PAINT)));
+       int needMapping = (ob==obact) && (editing || (ob->mode & (OB_MODE_WEIGHT_PAINT|OB_MODE_VERTEX_PAINT|OB_MODE_TEXTURE_PAINT)));
 
        clear_mesh_caches(ob);
 
        mesh_calc_modifiers(scene, ob, NULL, &ob->derivedDeform,
                                                &ob->derivedFinal, 0, 1,
 
        clear_mesh_caches(ob);
 
        mesh_calc_modifiers(scene, ob, NULL, &ob->derivedDeform,
                                                &ob->derivedFinal, 0, 1,
-                                               needMapping, dataMask, -1, 1);
+                                               needMapping, dataMask, -1, 1, build_shapekey_layers);
 
        DM_set_object_boundbox (ob, ob->derivedFinal);
 
 
        DM_set_object_boundbox (ob, ob->derivedFinal);
 
@@ -1378,7 +1839,7 @@ static void mesh_build_data(Scene *scene, Object *ob, CustomDataMask dataMask)
        ob->lastDataMask = dataMask;
 }
 
        ob->lastDataMask = dataMask;
 }
 
-static void editmesh_build_data(Scene *scene, Object *obedit, EditMesh *em, CustomDataMask dataMask)
+static void editbmesh_build_data(Scene *scene, Object *obedit, BMEditMesh *em, CustomDataMask dataMask)
 {
        clear_mesh_caches(obedit);
 
 {
        clear_mesh_caches(obedit);
 
@@ -1395,7 +1856,7 @@ static void editmesh_build_data(Scene *scene, Object *obedit, EditMesh *em, Cust
                em->derivedCage = NULL;
        }
 
                em->derivedCage = NULL;
        }
 
-       editmesh_calc_modifiers(scene, obedit, em, &em->derivedCage, &em->derivedFinal, dataMask);
+       editbmesh_calc_modifiers(scene, obedit, em, &em->derivedCage, &em->derivedFinal, dataMask);
        DM_set_object_boundbox (obedit, em->derivedFinal);
 
        em->lastDataMask = dataMask;
        DM_set_object_boundbox (obedit, em->derivedFinal);
 
        em->lastDataMask = dataMask;
@@ -1403,12 +1864,13 @@ static void editmesh_build_data(Scene *scene, Object *obedit, EditMesh *em, Cust
        em->derivedCage->needsFree = 0;
 }
 
        em->derivedCage->needsFree = 0;
 }
 
-void makeDerivedMesh(Scene *scene, Object *ob, EditMesh *em, CustomDataMask dataMask)
+void makeDerivedMesh(Scene *scene, Object *ob, BMEditMesh *em,
+       CustomDataMask dataMask, int build_shapekey_layers)
 {
        if (em) {
 {
        if (em) {
-               editmesh_build_data(scene, ob, em, dataMask);
+               editbmesh_build_data(scene, ob, em, dataMask);
        } else {
        } else {
-               mesh_build_data(scene, ob, dataMask);
+               mesh_build_data(scene, ob, dataMask, build_shapekey_layers);
        }
 }
 
        }
 }
 
@@ -1420,7 +1882,7 @@ DerivedMesh *mesh_get_derived_final(Scene *scene, Object *ob, CustomDataMask dat
         * the data we need, rebuild the derived mesh
         */
        if(!ob->derivedFinal || (dataMask & ob->lastDataMask) != dataMask)
         * the data we need, rebuild the derived mesh
         */
        if(!ob->derivedFinal || (dataMask & ob->lastDataMask) != dataMask)
-               mesh_build_data(scene, ob, dataMask);
+               mesh_build_data(scene, ob, dataMask, 0);
 
        return ob->derivedFinal;
 }
 
        return ob->derivedFinal;
 }
@@ -1431,7 +1893,7 @@ DerivedMesh *mesh_get_derived_deform(Scene *scene, Object *ob, CustomDataMask da
         * the data we need, rebuild the derived mesh
         */
        if(!ob->derivedDeform || (dataMask & ob->lastDataMask) != dataMask)
         * the data we need, rebuild the derived mesh
         */
        if(!ob->derivedDeform || (dataMask & ob->lastDataMask) != dataMask)
-               mesh_build_data(scene, ob, dataMask);
+               mesh_build_data(scene, ob, dataMask, 0);
 
        return ob->derivedDeform;
 }
 
        return ob->derivedDeform;
 }
@@ -1440,7 +1902,7 @@ DerivedMesh *mesh_create_derived_render(Scene *scene, Object *ob, CustomDataMask
 {
        DerivedMesh *final;
        
 {
        DerivedMesh *final;
        
-       mesh_calc_modifiers(scene, ob, NULL, NULL, &final, 1, 1, 0, dataMask, -1, 0);
+       mesh_calc_modifiers(scene, ob, NULL, NULL, &final, 1, 1, 0, dataMask, -1, 0, 0);
 
        return final;
 }
 
        return final;
 }
@@ -1449,7 +1911,7 @@ DerivedMesh *mesh_create_derived_index_render(Scene *scene, Object *ob, CustomDa
 {
        DerivedMesh *final;
        
 {
        DerivedMesh *final;
        
-       mesh_calc_modifiers(scene, ob, NULL, NULL, &final, 1, 1, 0, dataMask, index, 0);
+       mesh_calc_modifiers(scene, ob, NULL, NULL, &final, 1, 1, 0, dataMask, index, 0, 0);
 
        return final;
 }
 
        return final;
 }
@@ -1458,7 +1920,7 @@ DerivedMesh *mesh_create_derived_view(Scene *scene, Object *ob, CustomDataMask d
 {
        DerivedMesh *final;
 
 {
        DerivedMesh *final;
 
-       mesh_calc_modifiers(scene, ob, NULL, NULL, &final, 0, 1, 0, dataMask, -1, 0);
+       mesh_calc_modifiers(scene, ob, NULL, NULL, &final, 0, 1, 0, dataMask, -1, 0, 0);
 
        return final;
 }
 
        return final;
 }
@@ -1468,7 +1930,7 @@ DerivedMesh *mesh_create_derived_no_deform(Scene *scene, Object *ob, float (*ver
 {
        DerivedMesh *final;
        
 {
        DerivedMesh *final;
        
-       mesh_calc_modifiers(scene, ob, vertCos, NULL, &final, 0, 0, 0, dataMask, -1, 0);
+       mesh_calc_modifiers(scene, ob, vertCos, NULL, &final, 0, 0, 0, dataMask, -1, 0, 0);
 
        return final;
 }
 
        return final;
 }
@@ -1478,7 +1940,7 @@ DerivedMesh *mesh_create_derived_no_virtual(Scene *scene, Object *ob, float (*ve
 {
        DerivedMesh *final;
        
 {
        DerivedMesh *final;
        
-       mesh_calc_modifiers(scene, ob, vertCos, NULL, &final, 0, -1, 0, dataMask, -1, 0);
+       mesh_calc_modifiers(scene, ob, vertCos, NULL, &final, 0, -1, 0, dataMask, -1, 0, 0);
 
        return final;
 }
 
        return final;
 }
@@ -1488,7 +1950,7 @@ DerivedMesh *mesh_create_derived_physics(Scene *scene, Object *ob, float (*vertC
 {
        DerivedMesh *final;
        
 {
        DerivedMesh *final;
        
-       mesh_calc_modifiers(scene, ob, vertCos, NULL, &final, 0, -1, 1, dataMask, -1, 0);
+       mesh_calc_modifiers(scene, ob, vertCos, NULL, &final, 0, -1, 1, dataMask, -1, 0, 0);
 
        return final;
 }
 
        return final;
 }
@@ -1499,14 +1961,14 @@ DerivedMesh *mesh_create_derived_no_deform_render(Scene *scene, Object *ob,
 {
        DerivedMesh *final;
 
 {
        DerivedMesh *final;
 
-       mesh_calc_modifiers(scene, ob, vertCos, NULL, &final, 1, 0, 0, dataMask, -1, 0);
+       mesh_calc_modifiers(scene, ob, vertCos, NULL, &final, 1, 0, 0, dataMask, -1, 0, 0);
 
        return final;
 }
 
 /***/
 
 
        return final;
 }
 
 /***/
 
-DerivedMesh *editmesh_get_derived_cage_and_final(Scene *scene, Object *obedit, EditMesh *em, DerivedMesh **final_r,
+DerivedMesh *editbmesh_get_derived_cage_and_final(Scene *scene, Object *obedit, BMEditMesh *em, DerivedMesh **final_r,
                                                                                                 CustomDataMask dataMask)
 {
        /* if there's no derived mesh or the last data mask used doesn't include
                                                                                                 CustomDataMask dataMask)
 {
        /* if there's no derived mesh or the last data mask used doesn't include
@@ -1514,27 +1976,27 @@ DerivedMesh *editmesh_get_derived_cage_and_final(Scene *scene, Object *obedit, E
         */
        if(!em->derivedCage ||
           (em->lastDataMask & dataMask) != dataMask)
         */
        if(!em->derivedCage ||
           (em->lastDataMask & dataMask) != dataMask)
-               editmesh_build_data(scene, obedit, em, dataMask);
+               editbmesh_build_data(scene, obedit, em, dataMask);
 
        *final_r = em->derivedFinal;
        return em->derivedCage;
 }
 
 
        *final_r = em->derivedFinal;
        return em->derivedCage;
 }
 
-DerivedMesh *editmesh_get_derived_cage(Scene *scene, Object *obedit, EditMesh *em, CustomDataMask dataMask)
+DerivedMesh *editbmesh_get_derived_cage(Scene *scene, Object *obedit, BMEditMesh *em, CustomDataMask dataMask)
 {
        /* if there's no derived mesh or the last data mask used doesn't include
         * the data we need, rebuild the derived mesh
         */
        if(!em->derivedCage ||
           (em->lastDataMask & dataMask) != dataMask)
 {
        /* if there's no derived mesh or the last data mask used doesn't include
         * the data we need, rebuild the derived mesh
         */
        if(!em->derivedCage ||
           (em->lastDataMask & dataMask) != dataMask)
-               editmesh_build_data(scene, obedit, em, dataMask);
+               editbmesh_build_data(scene, obedit, em, dataMask);
 
        return em->derivedCage;
 }
 
 
        return em->derivedCage;
 }
 
-DerivedMesh *editmesh_get_derived_base(Object *UNUSED(obedit), EditMesh *em)
+DerivedMesh *editbmesh_get_derived_base(Object *obedit, BMEditMesh *em)
 {
 {
-       return editmesh_get_derived(em, NULL);
+       return getEditDerivedBMesh(em, obedit, NULL);
 }
 
 
 }
 
 
@@ -1574,7 +2036,7 @@ float *mesh_get_mapped_verts_nors(Scene *scene, Object *ob)
        if(ob->type!=OB_MESH || me->totvert==0)
                return NULL;
        
        if(ob->type!=OB_MESH || me->totvert==0)
                return NULL;
        
-       dm= mesh_get_derived_final(scene, ob, CD_MASK_BAREMESH);
+       dm= mesh_get_derived_final(scene, ob, CD_MASK_BAREMESH|CD_MASK_ORIGINDEX);
        vertexcosnos= MEM_callocN(6*sizeof(float)*me->totvert, "vertexcosnos map");
        
        if(dm->foreachMappedVert) {
        vertexcosnos= MEM_callocN(6*sizeof(float)*me->totvert, "vertexcosnos map");
        
        if(dm->foreachMappedVert) {
@@ -1604,7 +2066,7 @@ typedef struct
        MVert * mvert;          // vertices & normals
        float (*orco)[3];
        float (*tangent)[4];    // destination
        MVert * mvert;          // vertices & normals
        float (*orco)[3];
        float (*tangent)[4];    // destination
-       int numFaces;
+       int numTessFaces;
 
 } SGLSLMeshToTangent;
 
 
 } SGLSLMeshToTangent;
 
@@ -1614,7 +2076,7 @@ typedef struct
 static int GetNumFaces(const SMikkTSpaceContext * pContext)
 {
        SGLSLMeshToTangent * pMesh = (SGLSLMeshToTangent *) pContext->m_pUserData;
 static int GetNumFaces(const SMikkTSpaceContext * pContext)
 {
        SGLSLMeshToTangent * pMesh = (SGLSLMeshToTangent *) pContext->m_pUserData;
-       return pMesh->numFaces;
+       return pMesh->numTessFaces;
 }
 
 static int GetNumVertsOfFace(const SMikkTSpaceContext * pContext, const int face_num)
 }
 
 static int GetNumVertsOfFace(const SMikkTSpaceContext * pContext, const int face_num)
@@ -1703,15 +2165,15 @@ void DM_add_tangent_layer(DerivedMesh *dm)
        if(CustomData_get_layer_index(&dm->faceData, CD_TANGENT) != -1)
                return;
 
        if(CustomData_get_layer_index(&dm->faceData, CD_TANGENT) != -1)
                return;
 
-       nors = dm->getFaceDataArray(dm, CD_NORMAL);
+       nors = dm->getTessFaceDataArray(dm, CD_NORMAL);
 
        /* check we have all the needed layers */
        totvert= dm->getNumVerts(dm);
 
        /* check we have all the needed layers */
        totvert= dm->getNumVerts(dm);
-       totface= dm->getNumFaces(dm);
+       totface= dm->getNumTessFaces(dm);
 
        mvert= dm->getVertArray(dm);
 
        mvert= dm->getVertArray(dm);
-       mface= dm->getFaceArray(dm);
-       mtface= dm->getFaceDataArray(dm, CD_MTFACE);
+       mface= dm->getTessFaceArray(dm);
+       mtface= dm->getTessFaceDataArray(dm, CD_MTFACE);
 
        if(!mtface) {
                orco= dm->getVertDataArray(dm, CD_ORCO);
 
        if(!mtface) {
                orco= dm->getVertDataArray(dm, CD_ORCO);
@@ -1720,8 +2182,8 @@ void DM_add_tangent_layer(DerivedMesh *dm)
        }
        
        /* create tangent layer */
        }
        
        /* create tangent layer */
-       DM_add_face_layer(dm, CD_TANGENT, CD_CALLOC, NULL);
-       tangent= DM_get_face_data_layer(dm, CD_TANGENT);
+       DM_add_tessface_layer(dm, CD_TANGENT, CD_CALLOC, NULL);
+       tangent= DM_get_tessface_data_layer(dm, CD_TANGENT);
        
        /* allocate some space */
        arena= BLI_memarena_new(BLI_MEMARENA_STD_BUFSIZE, "tangent layer arena");
        
        /* allocate some space */
        arena= BLI_memarena_new(BLI_MEMARENA_STD_BUFSIZE, "tangent layer arena");
@@ -1741,7 +2203,7 @@ void DM_add_tangent_layer(DerivedMesh *dm)
                mesh2tangent.mvert = mvert;
                mesh2tangent.orco = orco;
                mesh2tangent.tangent = tangent;
                mesh2tangent.mvert = mvert;
                mesh2tangent.orco = orco;
                mesh2tangent.tangent = tangent;
-               mesh2tangent.numFaces = totface;
+               mesh2tangent.numTessFaces = totface;
 
                sContext.m_pUserData = &mesh2tangent;
                sContext.m_pInterface = &sInterface;
 
                sContext.m_pUserData = &mesh2tangent;
                sContext.m_pInterface = &sInterface;
@@ -1831,6 +2293,159 @@ void DM_add_tangent_layer(DerivedMesh *dm)
        MEM_freeN(vtangents);
 }
 
        MEM_freeN(vtangents);
 }
 
+void DM_calc_auto_bump_scale(DerivedMesh *dm)
+{
+       /* int totvert= dm->getNumVerts(dm); */ /* UNUSED */
+       int totface= dm->getNumTessFaces(dm);
+
+       MVert * mvert = dm->getVertArray(dm);
+       MFace * mface = dm->getTessFaceArray(dm);
+       MTFace * mtface = dm->getTessFaceDataArray(dm, CD_MTFACE);
+
+       if(mtface)
+       {
+               double dsum = 0.0;
+               int nr_accumulated = 0;
+               int f;
+
+               for ( f=0; f<totface; f++ )
+               {
+                       {
+                               float * verts[4], * tex_coords[4];
+                               const int nr_verts = mface[f].v4!=0 ? 4 : 3;
+                               int i, is_degenerate;
+
+                               verts[0]=mvert[mface[f].v1].co; verts[1]=mvert[mface[f].v2].co; verts[2]=mvert[mface[f].v3].co;
+                               tex_coords[0]=mtface[f].uv[0]; tex_coords[1]=mtface[f].uv[1]; tex_coords[2]=mtface[f].uv[2];
+                               if(nr_verts==4)
+                               {
+                                       verts[3]=mvert[mface[f].v4].co;
+                                       tex_coords[3]=mtface[f].uv[3];
+                               }
+
+                               // discard degenerate faces
+                               is_degenerate = 0;
+                               if(     equals_v3v3(verts[0], verts[1]) || equals_v3v3(verts[0], verts[2]) || equals_v3v3(verts[1], verts[2]) ||
+                                       equals_v2v2(tex_coords[0], tex_coords[1]) || equals_v2v2(tex_coords[0], tex_coords[2]) || equals_v2v2(tex_coords[1], tex_coords[2]) )
+                               {
+                                       is_degenerate = 1;
+                               }
+
+                               // verify last vertex as well if this is a quad
+                               if ( is_degenerate==0 && nr_verts==4 )
+                               {
+                                       if(     equals_v3v3(verts[3], verts[0]) || equals_v3v3(verts[3], verts[1]) || equals_v3v3(verts[3], verts[2]) ||
+                                               equals_v2v2(tex_coords[3], tex_coords[0]) || equals_v2v2(tex_coords[3], tex_coords[1]) || equals_v2v2(tex_coords[3], tex_coords[2]) )
+                                       {
+                                               is_degenerate = 1;
+                                       }
+
+                                       // verify the winding is consistent
+                                       if ( is_degenerate==0 )
+                                       {
+                                               float prev_edge[2];
+                                               int is_signed = 0;
+                                               sub_v2_v2v2(prev_edge, tex_coords[0], tex_coords[3]);
+
+                                               i = 0;
+                                               while ( is_degenerate==0 && i<4 )
+                                               {
+                                                       float cur_edge[2], signed_area;
+                                                       sub_v2_v2v2(cur_edge, tex_coords[(i+1)&0x3], tex_coords[i]);
+                                                       signed_area = prev_edge[0]*cur_edge[1] - prev_edge[1]*cur_edge[0];
+                                                       if ( i==0 ) is_signed = signed_area<0.0f ? 1 : 0;
+                                                       else if((is_signed!=0)!=(signed_area<0.0f)) is_degenerate=1;
+
+                                                       if ( is_degenerate==0 )
+                                                       {
+                                                               copy_v2_v2(prev_edge, cur_edge);
+                                                               ++i;
+                                                       }
+                                               }
+                                       }
+                               }
+
+                               // proceed if not a degenerate face
+                               if ( is_degenerate==0 )
+                               {
+                                       int nr_tris_to_pile=0;
+                                       // quads split at shortest diagonal
+                                       int offs = 0;           // initial triangulation is 0,1,2 and 0, 2, 3
+                                       if ( nr_verts==4 )
+                                       {
+                                               float pos_len_diag0, pos_len_diag1;
+                                               float vtmp[3];
+                                               sub_v3_v3v3(vtmp, verts[2], verts[0]);
+                                               pos_len_diag0 = dot_v3v3(vtmp, vtmp);
+                                               sub_v3_v3v3(vtmp, verts[3], verts[1]);
+                                               pos_len_diag1 = dot_v3v3(vtmp, vtmp);
+
+                                               if(pos_len_diag1<pos_len_diag0)
+                                                       offs=1;         // alter split
+                                               else if(pos_len_diag0==pos_len_diag1)           // do UV check instead
+                                               {
+                                                       float tex_len_diag0, tex_len_diag1;
+
+                                                       sub_v2_v2v2(vtmp, tex_coords[2], tex_coords[0]);
+                                                       tex_len_diag0 = dot_v2v2(vtmp, vtmp);
+                                                       sub_v2_v2v2(vtmp, tex_coords[3], tex_coords[1]);
+                                                       tex_len_diag1 = dot_v2v2(vtmp, vtmp);
+
+                                                       if(tex_len_diag1<tex_len_diag0)
+                                                       {
+                                                               offs=1;         // alter split
+                                                       }
+                                               }
+                                       }
+                                       nr_tris_to_pile = nr_verts-2 ;
+                                       if ( nr_tris_to_pile==1 || nr_tris_to_pile==2 )
+                                       {
+                                               const int indices[] = {offs+0, offs+1, offs+2, offs+0, offs+2, (offs+3)&0x3 };
+                                               int t;
+                                               for ( t=0; t<nr_tris_to_pile; t++ )
+                                               {
+                                                       float f2x_area_uv;
+                                                       float * p0 = verts[indices[t*3+0]];
+                                                       float * p1 = verts[indices[t*3+1]];
+                                                       float * p2 = verts[indices[t*3+2]];
+
+                                                       float edge_t0[2], edge_t1[2];
+                                                       sub_v2_v2v2(edge_t0, tex_coords[indices[t*3+1]], tex_coords[indices[t*3+0]]);
+                                                       sub_v2_v2v2(edge_t1, tex_coords[indices[t*3+2]], tex_coords[indices[t*3+0]]);
+
+                                                       f2x_area_uv = fabsf(edge_t0[0]*edge_t1[1] - edge_t0[1]*edge_t1[0]);
+                                                       if ( f2x_area_uv>FLT_EPSILON )
+                                                       {
+                                                               float norm[3], v0[3], v1[3], f2x_surf_area, fsurf_ratio;
+                                                               sub_v3_v3v3(v0, p1, p0);
+                                                               sub_v3_v3v3(v1, p2, p0);
+                                                               cross_v3_v3v3(norm, v0, v1);
+
+                                                               f2x_surf_area = len_v3(norm);
+                                                               fsurf_ratio = f2x_surf_area/f2x_area_uv;        // tri area divided by texture area
+
+                                                               ++nr_accumulated;
+                                                               dsum += (double)(fsurf_ratio);
+                                                       }
+                                               }
+                                       }
+                               }
+                       }
+               }
+
+               // finalize
+               {
+                       const float avg_area_ratio = (nr_accumulated>0) ? ((float)(dsum / nr_accumulated)) : 1.0f;
+                       const float use_as_render_bump_scale = sqrtf(avg_area_ratio);           // use width of average surface ratio as your bump scale
+                       dm->auto_bump_scale = use_as_render_bump_scale;
+               }
+       }
+       else
+       {
+               dm->auto_bump_scale = 1.0f;
+       }
+}
+
 void DM_vertex_attributes_from_gpu(DerivedMesh *dm, GPUVertexAttribs *gattribs, DMVertexAttribs *attribs)
 {
        CustomData *vdata, *fdata, *tfdata = NULL;
 void DM_vertex_attributes_from_gpu(DerivedMesh *dm, GPUVertexAttribs *gattribs, DMVertexAttribs *attribs)
 {
        CustomData *vdata, *fdata, *tfdata = NULL;
@@ -1842,14 +2457,11 @@ void DM_vertex_attributes_from_gpu(DerivedMesh *dm, GPUVertexAttribs *gattribs,
        memset(attribs, 0, sizeof(DMVertexAttribs));
 
        vdata = &dm->vertData;
        memset(attribs, 0, sizeof(DMVertexAttribs));
 
        vdata = &dm->vertData;
-       fdata = &dm->faceData;
-
-       /* ugly hack, editmesh derivedmesh doesn't copy face data, this way we
-        * can use offsets instead */
-       if(dm->type == DM_TYPE_EDITMESH)
-               tfdata = &((EditMeshDerivedMesh*)dm)->em->fdata;
-       else
-               tfdata = fdata;
+       fdata = tfdata = dm->getTessFaceDataLayout(dm);
+       
+       /* calc auto bump scale if necessary */
+       if(dm->auto_bump_scale<=0.0f)
+               DM_calc_auto_bump_scale(dm);
 
        /* add a tangent layer if necessary */
        for(b = 0; b < gattribs->totlayer; b++)
 
        /* add a tangent layer if necessary */
        for(b = 0; b < gattribs->totlayer; b++)
@@ -1872,8 +2484,30 @@ void DM_vertex_attributes_from_gpu(DerivedMesh *dm, GPUVertexAttribs *gattribs,
                                attribs->tface[a].array = tfdata->layers[layer].data;
                                attribs->tface[a].emOffset = tfdata->layers[layer].offset;
                                attribs->tface[a].glIndex = gattribs->layer[b].glindex;
                                attribs->tface[a].array = tfdata->layers[layer].data;
                                attribs->tface[a].emOffset = tfdata->layers[layer].offset;
                                attribs->tface[a].glIndex = gattribs->layer[b].glindex;
-                               attribs->tface[a].glTexco = gattribs->layer[b].gltexco;
+                               /* attribs->tface[a].glTexco = gattribs->layer[b].gltexco; */ /* BMESH_TODO, trunk has this but not bmesh, need to investigate whats going on here - campbell */
                        }
                        }
+                       /* BMESH ONLY, may need to get this working?, otherwise remove */
+                       /* else {
+                               int player;
+                               CustomData *pdata = dm->getPolyDataLayout(dm);
+                               
+                               if(gattribs->layer[b].name[0])
+                                       player = CustomData_get_named_layer_index(pdata, CD_MTEXPOLY,
+                                               gattribs->layer[b].name);
+                               else
+                                       player = CustomData_get_active_layer_index(pdata, CD_MTEXPOLY);
+                               
+                               if (player != -1) {
+                                       a = attribs->tottface++;
+       
+                                       attribs->tface[a].array = NULL;
+                                       attribs->tface[a].emOffset = pdata->layers[layer].offset;
+                                       attribs->tface[a].glIndex = gattribs->layer[b].glindex;
+                                       attribs->tface[a].glTexco = gattribs->layer[b].gltexco;
+                                       
+                               }
+                       }
+                       */
                }
                else if(gattribs->layer[b].type == CD_MCOL) {
                        /* vertex colors */
                }
                else if(gattribs->layer[b].type == CD_MCOL) {
                        /* vertex colors */
@@ -1976,7 +2610,7 @@ static void navmesh_drawColored(DerivedMesh *dm)
                DEBUG_VBO( "Using legacy code. drawNavMeshColored\n" );
                //glShadeModel(GL_SMOOTH);
                glBegin(glmode = GL_QUADS);
                DEBUG_VBO( "Using legacy code. drawNavMeshColored\n" );
                //glShadeModel(GL_SMOOTH);
                glBegin(glmode = GL_QUADS);
-               for(a = 0; a < dm->numFaceData; a++, mface++) {
+               for(a = 0; a < dm->numTessFaceData; a++, mface++) {
                        int new_glmode = mface->v4?GL_QUADS:GL_TRIANGLES;
                        int pi = polygonIdx[a];
                        if (pi <= 0) {
                        int new_glmode = mface->v4?GL_QUADS:GL_TRIANGLES;
                        int pi = polygonIdx[a];
                        if (pi <= 0) {
@@ -2029,7 +2663,7 @@ static void navmesh_DM_drawFacesSolid(DerivedMesh *dm,
 static DerivedMesh *navmesh_dm_createNavMeshForVisualization(DerivedMesh *dm)
 {
        DerivedMesh *result;
 static DerivedMesh *navmesh_dm_createNavMeshForVisualization(DerivedMesh *dm)
 {
        DerivedMesh *result;
-       int maxFaces = dm->getNumFaces(dm);
+       int maxFaces = dm->getNumPolys(dm);
        int *recastData;
        int vertsPerPoly=0, nverts=0, ndtris=0, npolys=0;
        float* verts=NULL;
        int *recastData;
        int vertsPerPoly=0, nverts=0, ndtris=0, npolys=0;
        float* verts=NULL;
@@ -2037,7 +2671,7 @@ static DerivedMesh *navmesh_dm_createNavMeshForVisualization(DerivedMesh *dm)
        int *dtrisToPolysMap=NULL, *dtrisToTrisMap=NULL, *trisToFacesMap=NULL;
        int res;
 
        int *dtrisToPolysMap=NULL, *dtrisToTrisMap=NULL, *trisToFacesMap=NULL;
        int res;
 
-       result = CDDM_copy(dm);
+       result = CDDM_copy(dm, 0);
        if (!CustomData_has_layer(&result->faceData, CD_RECAST)) {
                int *sourceRecastData = (int*)CustomData_get_layer(&dm->faceData, CD_RECAST);
                if (sourceRecastData) {
        if (!CustomData_has_layer(&result->faceData, CD_RECAST)) {
                int *sourceRecastData = (int*)CustomData_get_layer(&dm->faceData, CD_RECAST);
                if (sourceRecastData) {
@@ -2105,3 +2739,84 @@ static DerivedMesh *navmesh_dm_createNavMeshForVisualization(DerivedMesh *dm)
 #endif /* WITH_GAMEENGINE */
 
 /* --- NAVMESH (end) --- */
 #endif /* WITH_GAMEENGINE */
 
 /* --- NAVMESH (end) --- */
+
+
+/* derivedmesh info printing function,
+ * to help track down differences DM output */
+
+#ifndef NDEBUG
+#include "BLI_dynstr.h"
+
+static void dm_debug_info_layers(DynStr *dynstr, DerivedMesh *dm, void *(*getElemDataArray)(DerivedMesh *, int))
+{
+       int type;
+
+       for (type = 0; type < CD_NUMTYPES; type++) {
+               /* note: doesnt account for multiple layers */
+               void *pt = getElemDataArray(dm, type);
+               if (pt) {
+                       const char *name = CustomData_layertype_name(type);
+                       const int size = CustomData_sizeof(type);
+                       const char *structname;
+                       int structnum;
+                       CustomData_file_write_info(type, &structname, &structnum);
+                       BLI_dynstr_appendf(dynstr,
+                                          "        dict(name='%s', struct='%s', type=%d, ptr='%p', elem=%d, length=%d),\n",
+                                                          name, structname, type, (void *)pt, size, (int)(MEM_allocN_len(pt) / size));
+               }
+       }
+}
+
+char *DM_debug_info(DerivedMesh *dm)
+{
+       DynStr *dynstr= BLI_dynstr_new();
+       char *ret;
+       const char *tstr;
+
+       BLI_dynstr_appendf(dynstr, "{\n");
+       BLI_dynstr_appendf(dynstr, "    'ptr': '%p',\n", (void *)dm);
+       switch (dm->type) {
+               case DM_TYPE_CDDM:     tstr = "DM_TYPE_CDDM";     break;
+               case DM_TYPE_EDITBMESH: tstr = "DM_TYPE_EDITMESH";  break;
+               case DM_TYPE_CCGDM:    tstr = "DM_TYPE_CCGDM";     break;
+               default:               tstr = "UNKNOWN";           break;
+       }
+       BLI_dynstr_appendf(dynstr, "    'type': '%s',\n", tstr);
+       BLI_dynstr_appendf(dynstr, "    'numVertData': %d,\n", dm->numVertData);
+       BLI_dynstr_appendf(dynstr, "    'numEdgeData': %d,\n", dm->numEdgeData);
+       BLI_dynstr_appendf(dynstr, "    'numTessFaceData': %d,\n", dm->numTessFaceData);
+       BLI_dynstr_appendf(dynstr, "    'numPolyData': %d,\n", dm->numPolyData);
+       BLI_dynstr_appendf(dynstr, "    'deformedOnly': %d,\n", dm->deformedOnly);
+
+       BLI_dynstr_appendf(dynstr, "    'vertexLayers': (\n");
+       dm_debug_info_layers(dynstr, dm, dm->getVertDataArray);
+       BLI_dynstr_appendf(dynstr, "    ),\n");
+
+       BLI_dynstr_appendf(dynstr, "    'edgeLayers': (\n");
+       dm_debug_info_layers(dynstr, dm, dm->getEdgeDataArray);
+       BLI_dynstr_appendf(dynstr, "    ),\n");
+
+       BLI_dynstr_appendf(dynstr, "    'tessFaceLayers': (\n");
+       dm_debug_info_layers(dynstr, dm, dm->getTessFaceDataArray);
+       BLI_dynstr_appendf(dynstr, "    ),\n");
+
+       BLI_dynstr_appendf(dynstr, "    'PolyLayers': (\n");
+       dm_debug_info_layers(dynstr, dm, DM_get_poly_data_layer);
+       BLI_dynstr_appendf(dynstr, "    ),\n");
+
+       BLI_dynstr_appendf(dynstr, "}\n");
+
+       ret = BLI_dynstr_get_cstring(dynstr);
+       BLI_dynstr_free(dynstr);
+       return ret;
+}
+
+void DM_debug_print(DerivedMesh *dm)
+{
+       char *str = DM_debug_info(dm);
+       printf("%s", str);
+       fflush(stdout);
+       MEM_freeN(str);
+}
+
+#endif /* NDEBUG */