OpenSubdiv: Properly respect Subdivide UVs option
[blender.git] / source / blender / blenkernel / intern / subsurf_ccg.c
1 /*
2  * ***** BEGIN GPL LICENSE BLOCK *****
3  *
4  * This program is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU General Public License
6  * as published by the Free Software Foundation; either version 2
7  * of the License, or (at your option) any later version.
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with this program; if not, write to the Free Software Foundation,
16  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
17  *
18  * The Original Code is Copyright (C) 2005 Blender Foundation.
19  * All rights reserved.
20  *
21  * The Original Code is: all of this file.
22  *
23  * Contributor(s): none yet.
24  *
25  * ***** END GPL LICENSE BLOCK *****
26  */
27
28 /** \file blender/blenkernel/intern/subsurf_ccg.c
29  *  \ingroup bke
30  */
31
32 #if defined(__STDC_VERSION__) && __STDC_VERSION__ >= 199901L
33 #  ifdef __GNUC__
34 #    pragma GCC diagnostic ignored "-Wvla"
35 #  endif
36 #  define USE_DYNSIZE
37 #endif
38
39 #include <stdlib.h>
40 #include <string.h>
41 #include <stdio.h>
42 #include <math.h>
43 #include <float.h>
44
45 #include "MEM_guardedalloc.h"
46
47 #include "DNA_mesh_types.h"
48 #include "DNA_meshdata_types.h"
49 #include "DNA_modifier_types.h"
50 #include "DNA_object_types.h"
51 #include "DNA_scene_types.h"
52
53 #include "BLI_utildefines.h"
54 #include "BLI_bitmap.h"
55 #include "BLI_blenlib.h"
56 #include "BLI_edgehash.h"
57 #include "BLI_math.h"
58 #include "BLI_memarena.h"
59 #include "BLI_threads.h"
60
61 #include "BKE_pbvh.h"
62 #include "BKE_ccg.h"
63 #include "BKE_cdderivedmesh.h"
64 #include "BKE_global.h"
65 #include "BKE_mesh.h"
66 #include "BKE_mesh_mapping.h"
67 #include "BKE_multires.h"
68 #include "BKE_paint.h"
69 #include "BKE_scene.h"
70 #include "BKE_subsurf.h"
71
72 #ifndef USE_DYNSIZE
73 #  include "BLI_array.h"
74 #endif
75
76 #include "GPU_draw.h"
77 #include "GPU_glew.h"
78 #include "GPU_buffers.h"
79 #include "GPU_shader.h"
80 #include "GPU_basic_shader.h"
81
82 #include "CCGSubSurf.h"
83
84 #ifdef WITH_OPENSUBDIV
85 #  include "opensubdiv_capi.h"
86 #endif
87
88 /* assumes MLoop's are layed out 4 for each poly, in order */
89 #define USE_LOOP_LAYOUT_FAST
90
91 static ThreadRWMutex loops_cache_rwlock = BLI_RWLOCK_INITIALIZER;
92 static ThreadRWMutex origindex_cache_rwlock = BLI_RWLOCK_INITIALIZER;
93
94 static CCGDerivedMesh *getCCGDerivedMesh(CCGSubSurf *ss,
95                                          int drawInteriorEdges,
96                                          int useSubsurfUv,
97                                          DerivedMesh *dm,
98                                          bool use_gpu_backend);
99 static int ccgDM_use_grid_pbvh(CCGDerivedMesh *ccgdm);
100
101 ///
102
103 static void *arena_alloc(CCGAllocatorHDL a, int numBytes)
104 {
105         return BLI_memarena_alloc(a, numBytes);
106 }
107
108 static void *arena_realloc(CCGAllocatorHDL a, void *ptr, int newSize, int oldSize)
109 {
110         void *p2 = BLI_memarena_alloc(a, newSize);
111         if (ptr) {
112                 memcpy(p2, ptr, oldSize);
113         }
114         return p2;
115 }
116
117 static void arena_free(CCGAllocatorHDL UNUSED(a), void *UNUSED(ptr))
118 {
119         /* do nothing */
120 }
121
122 static void arena_release(CCGAllocatorHDL a)
123 {
124         BLI_memarena_free(a);
125 }
126
127 typedef enum {
128         CCG_USE_AGING = 1,
129         CCG_USE_ARENA = 2,
130         CCG_CALC_NORMALS = 4,
131         /* add an extra four bytes for a mask layer */
132         CCG_ALLOC_MASK = 8,
133         CCG_SIMPLE_SUBDIV = 16
134 } CCGFlags;
135
136 static CCGSubSurf *_getSubSurf(CCGSubSurf *prevSS, int subdivLevels,
137                                int numLayers, CCGFlags flags)
138 {
139         CCGMeshIFC ifc;
140         CCGSubSurf *ccgSS;
141         int useAging = !!(flags & CCG_USE_AGING);
142         int useArena = flags & CCG_USE_ARENA;
143         int normalOffset = 0;
144
145         /* (subdivLevels == 0) is not allowed */
146         subdivLevels = MAX2(subdivLevels, 1);
147
148         if (prevSS) {
149                 int oldUseAging;
150
151                 ccgSubSurf_getUseAgeCounts(prevSS, &oldUseAging, NULL, NULL, NULL);
152
153                 if ((oldUseAging != useAging) ||
154                     (ccgSubSurf_getSimpleSubdiv(prevSS) != !!(flags & CCG_SIMPLE_SUBDIV)))
155                 {
156                         ccgSubSurf_free(prevSS);
157                 }
158                 else {
159                         ccgSubSurf_setSubdivisionLevels(prevSS, subdivLevels);
160
161                         return prevSS;
162                 }
163         }
164
165         if (useAging) {
166                 ifc.vertUserSize = ifc.edgeUserSize = ifc.faceUserSize = 12;
167         }
168         else {
169                 ifc.vertUserSize = ifc.edgeUserSize = ifc.faceUserSize = 8;
170         }
171         ifc.numLayers = numLayers;
172         ifc.vertDataSize = sizeof(float) * numLayers;
173         normalOffset += sizeof(float) * numLayers;
174         if (flags & CCG_CALC_NORMALS)
175                 ifc.vertDataSize += sizeof(float) * 3;
176         if (flags & CCG_ALLOC_MASK)
177                 ifc.vertDataSize += sizeof(float);
178         ifc.simpleSubdiv = !!(flags & CCG_SIMPLE_SUBDIV);
179
180         if (useArena) {
181                 CCGAllocatorIFC allocatorIFC;
182                 CCGAllocatorHDL allocator = BLI_memarena_new(MEM_SIZE_OPTIMAL(1 << 16), "subsurf arena");
183
184                 allocatorIFC.alloc = arena_alloc;
185                 allocatorIFC.realloc = arena_realloc;
186                 allocatorIFC.free = arena_free;
187                 allocatorIFC.release = arena_release;
188
189                 ccgSS = ccgSubSurf_new(&ifc, subdivLevels, &allocatorIFC, allocator);
190         }
191         else {
192                 ccgSS = ccgSubSurf_new(&ifc, subdivLevels, NULL, NULL);
193         }
194
195         if (useAging) {
196                 ccgSubSurf_setUseAgeCounts(ccgSS, 1, 8, 8, 8);
197         }
198
199         if (flags & CCG_ALLOC_MASK) {
200                 normalOffset += sizeof(float);
201                 /* mask is allocated after regular layers */
202                 ccgSubSurf_setAllocMask(ccgSS, 1, sizeof(float) * numLayers);
203         }
204         
205         if (flags & CCG_CALC_NORMALS)
206                 ccgSubSurf_setCalcVertexNormals(ccgSS, 1, normalOffset);
207         else
208                 ccgSubSurf_setCalcVertexNormals(ccgSS, 0, 0);
209
210         return ccgSS;
211 }
212
213 static int getEdgeIndex(CCGSubSurf *ss, CCGEdge *e, int x, int edgeSize)
214 {
215         CCGVert *v0 = ccgSubSurf_getEdgeVert0(e);
216         CCGVert *v1 = ccgSubSurf_getEdgeVert1(e);
217         int v0idx = *((int *) ccgSubSurf_getVertUserData(ss, v0));
218         int v1idx = *((int *) ccgSubSurf_getVertUserData(ss, v1));
219         int edgeBase = *((int *) ccgSubSurf_getEdgeUserData(ss, e));
220
221         if (x == 0) {
222                 return v0idx;
223         }
224         else if (x == edgeSize - 1) {
225                 return v1idx;
226         }
227         else {
228                 return edgeBase + x - 1;
229         }
230 }
231
232 static int getFaceIndex(CCGSubSurf *ss, CCGFace *f, int S, int x, int y, int edgeSize, int gridSize)
233 {
234         int faceBase = *((int *) ccgSubSurf_getFaceUserData(ss, f));
235         int numVerts = ccgSubSurf_getFaceNumVerts(f);
236
237         if (x == gridSize - 1 && y == gridSize - 1) {
238                 CCGVert *v = ccgSubSurf_getFaceVert(f, S);
239                 return *((int *) ccgSubSurf_getVertUserData(ss, v));
240         }
241         else if (x == gridSize - 1) {
242                 CCGVert *v = ccgSubSurf_getFaceVert(f, S);
243                 CCGEdge *e = ccgSubSurf_getFaceEdge(f, S);
244                 int edgeBase = *((int *) ccgSubSurf_getEdgeUserData(ss, e));
245                 if (v == ccgSubSurf_getEdgeVert0(e)) {
246                         return edgeBase + (gridSize - 1 - y) - 1;
247                 }
248                 else {
249                         return edgeBase + (edgeSize - 2 - 1) - ((gridSize - 1 - y) - 1);
250                 }
251         }
252         else if (y == gridSize - 1) {
253                 CCGVert *v = ccgSubSurf_getFaceVert(f, S);
254                 CCGEdge *e = ccgSubSurf_getFaceEdge(f, (S + numVerts - 1) % numVerts);
255                 int edgeBase = *((int *) ccgSubSurf_getEdgeUserData(ss, e));
256                 if (v == ccgSubSurf_getEdgeVert0(e)) {
257                         return edgeBase + (gridSize - 1 - x) - 1;
258                 }
259                 else {
260                         return edgeBase + (edgeSize - 2 - 1) - ((gridSize - 1 - x) - 1);
261                 }
262         }
263         else if (x == 0 && y == 0) {
264                 return faceBase;
265         }
266         else if (x == 0) {
267                 S = (S + numVerts - 1) % numVerts;
268                 return faceBase + 1 + (gridSize - 2) * S + (y - 1);
269         }
270         else if (y == 0) {
271                 return faceBase + 1 + (gridSize - 2) * S + (x - 1);
272         }
273         else {
274                 return faceBase + 1 + (gridSize - 2) * numVerts + S * (gridSize - 2) * (gridSize - 2) + (y - 1) * (gridSize - 2) + (x - 1);
275         }
276 }
277
278 static void get_face_uv_map_vert(UvVertMap *vmap, struct MPoly *mpoly, struct MLoop *ml, int fi, CCGVertHDL *fverts)
279 {
280         UvMapVert *v, *nv;
281         int j, nverts = mpoly[fi].totloop;
282
283         for (j = 0; j < nverts; j++) {
284                 for (nv = v = BKE_mesh_uv_vert_map_get_vert(vmap, ml[j].v); v; v = v->next) {
285                         if (v->separate)
286                                 nv = v;
287                         if (v->f == fi)
288                                 break;
289                 }
290
291                 fverts[j] = SET_UINT_IN_POINTER(mpoly[nv->f].loopstart + nv->tfindex);
292         }
293 }
294
295 static int ss_sync_from_uv(CCGSubSurf *ss, CCGSubSurf *origss, DerivedMesh *dm, MLoopUV *mloopuv)
296 {
297         MPoly *mpoly = dm->getPolyArray(dm);
298         MLoop *mloop = dm->getLoopArray(dm);
299         MVert *mvert = dm->getVertArray(dm);
300         int totvert = dm->getNumVerts(dm);
301         int totface = dm->getNumPolys(dm);
302         int i, seam;
303         UvMapVert *v;
304         UvVertMap *vmap;
305         float limit[2];
306 #ifndef USE_DYNSIZE
307         CCGVertHDL *fverts = NULL;
308         BLI_array_declare(fverts);
309 #endif
310         EdgeSet *eset;
311         float creaseFactor = (float)ccgSubSurf_getSubdivisionLevels(ss);
312         float uv[3] = {0.0f, 0.0f, 0.0f}; /* only first 2 values are written into */
313
314         limit[0] = limit[1] = STD_UV_CONNECT_LIMIT;
315         /* previous behavior here is without accounting for winding, however this causes stretching in
316          * UV map in really simple cases with mirror + subsurf, see second part of T44530. Also, initially
317          * intention is to treat merged vertices from mirror modifier as seams, see code below with ME_VERT_MERGED
318          * This fixes a very old regression (2.49 was correct here) */
319         vmap = BKE_mesh_uv_vert_map_create(mpoly, mloop, mloopuv, totface, totvert, limit, false, true);
320         if (!vmap)
321                 return 0;
322         
323         ccgSubSurf_initFullSync(ss);
324
325         /* create vertices */
326         for (i = 0; i < totvert; i++) {
327                 if (!BKE_mesh_uv_vert_map_get_vert(vmap, i))
328                         continue;
329
330                 for (v = BKE_mesh_uv_vert_map_get_vert(vmap, i)->next; v; v = v->next)
331                         if (v->separate)
332                                 break;
333
334                 seam = (v != NULL) || ((mvert + i)->flag & ME_VERT_MERGED);
335
336                 for (v = BKE_mesh_uv_vert_map_get_vert(vmap, i); v; v = v->next) {
337                         if (v->separate) {
338                                 CCGVert *ssv;
339                                 int loopid = mpoly[v->f].loopstart + v->tfindex;
340                                 CCGVertHDL vhdl = SET_INT_IN_POINTER(loopid);
341
342                                 copy_v2_v2(uv, mloopuv[loopid].uv);
343
344                                 ccgSubSurf_syncVert(ss, vhdl, uv, seam, &ssv);
345                         }
346                 }
347         }
348
349         /* create edges */
350         eset = BLI_edgeset_new_ex(__func__, BLI_EDGEHASH_SIZE_GUESS_FROM_POLYS(totface));
351
352         for (i = 0; i < totface; i++) {
353                 MPoly *mp = &mpoly[i];
354                 int nverts = mp->totloop;
355                 int j, j_next;
356                 CCGFace *origf = ccgSubSurf_getFace(origss, SET_INT_IN_POINTER(i));
357                 /* unsigned int *fv = &mp->v1; */
358                 MLoop *ml = mloop + mp->loopstart;
359
360 #ifdef USE_DYNSIZE
361                 CCGVertHDL fverts[nverts];
362 #else
363                 BLI_array_empty(fverts);
364                 BLI_array_grow_items(fverts, nverts);
365 #endif
366
367                 get_face_uv_map_vert(vmap, mpoly, ml, i, fverts);
368
369                 for (j = 0, j_next = nverts - 1; j < nverts; j_next = j++) {
370                         unsigned int v0 = GET_UINT_FROM_POINTER(fverts[j_next]);
371                         unsigned int v1 = GET_UINT_FROM_POINTER(fverts[j]);
372                         MVert *mv0 = mvert + (ml[j_next].v);
373                         MVert *mv1 = mvert + (ml[j].v);
374
375                         if (BLI_edgeset_add(eset, v0, v1)) {
376                                 CCGEdge *e, *orige = ccgSubSurf_getFaceEdge(origf, j_next);
377                                 CCGEdgeHDL ehdl = SET_INT_IN_POINTER(mp->loopstart + j_next);
378                                 float crease;
379
380                                 if ((mv0->flag & mv1->flag) & ME_VERT_MERGED)
381                                         crease = creaseFactor;
382                                 else
383                                         crease = ccgSubSurf_getEdgeCrease(orige);
384
385                                 ccgSubSurf_syncEdge(ss, ehdl, fverts[j_next], fverts[j], crease, &e);
386                         }
387                 }
388         }
389
390         BLI_edgeset_free(eset);
391
392         /* create faces */
393         for (i = 0; i < totface; i++) {
394                 MPoly *mp = &mpoly[i];
395                 MLoop *ml = &mloop[mp->loopstart];
396                 int nverts = mp->totloop;
397                 CCGFace *f;
398
399 #ifdef USE_DYNSIZE
400                 CCGVertHDL fverts[nverts];
401 #else
402                 BLI_array_empty(fverts);
403                 BLI_array_grow_items(fverts, nverts);
404 #endif
405
406                 get_face_uv_map_vert(vmap, mpoly, ml, i, fverts);
407                 ccgSubSurf_syncFace(ss, SET_INT_IN_POINTER(i), nverts, fverts, &f);
408         }
409
410 #ifndef USE_DYNSIZE
411         BLI_array_free(fverts);
412 #endif
413
414         BKE_mesh_uv_vert_map_free(vmap);
415         ccgSubSurf_processSync(ss);
416
417         return 1;
418 }
419
420 #ifdef WITH_OPENSUBDIV
421 static void UNUSED_FUNCTION(set_subsurf_osd_ccg_uv)(CCGSubSurf *ss,
422                                                     DerivedMesh *dm,
423                                                     DerivedMesh *result,
424                                                     int layer_index)
425 {
426         CCGFace **faceMap;
427         MTFace *tf;
428         MLoopUV *mluv;
429         CCGFaceIterator fi;
430         int index, gridSize, gridFaces, totface, x, y, S;
431         MLoopUV *dmloopuv = CustomData_get_layer_n(&dm->loopData, CD_MLOOPUV, layer_index);
432         /* need to update both CD_MTFACE & CD_MLOOPUV, hrmf, we could get away with
433          * just tface except applying the modifier then looses subsurf UV */
434         MTFace *tface = CustomData_get_layer_n(&result->faceData, CD_MTFACE, layer_index);
435         MLoopUV *mloopuv = CustomData_get_layer_n(&result->loopData, CD_MLOOPUV, layer_index);
436
437         if (dmloopuv == NULL || (tface == NULL && mloopuv == NULL)) {
438                 return;
439         }
440
441         ccgSubSurf_evaluatorSetFVarUV(ss, dm, layer_index);
442
443         /* get some info from CCGSubSurf */
444         totface = ccgSubSurf_getNumFaces(ss);
445         gridSize = ccgSubSurf_getGridSize(ss);
446         gridFaces = gridSize - 1;
447
448         /* make a map from original faces to CCGFaces */
449         faceMap = MEM_mallocN(totface * sizeof(*faceMap), "facemapuv");
450         for (ccgSubSurf_initFaceIterator(ss, &fi); !ccgFaceIterator_isStopped(&fi); ccgFaceIterator_next(&fi)) {
451                 CCGFace *f = ccgFaceIterator_getCurrent(&fi);
452                 faceMap[GET_INT_FROM_POINTER(ccgSubSurf_getFaceFaceHandle(f))] = f;
453         }
454
455         /* load coordinates from uvss into tface */
456         tf = tface;
457         mluv = mloopuv;
458         for (index = 0; index < totface; index++) {
459                 CCGFace *f = faceMap[index];
460                 int numVerts = ccgSubSurf_getFaceNumVerts(f);
461                 for (S = 0; S < numVerts; S++) {
462                         for (y = 0; y < gridFaces; y++) {
463                                 for (x = 0; x < gridFaces; x++) {
464                                         const int delta[4][2] = {{0, 0},
465                                                                  {0, 1},
466                                                                  {1, 1},
467                                                                  {1, 0}};
468                                         float uv[4][2];
469                                         int i;
470                                         for (i = 0; i < 4; i++) {
471                                                 const int dx = delta[i][0],
472                                                           dy = delta[i][1];
473                                                 const float grid_u = ((float)(x + dx)) / (gridSize - 1),
474                                                             grid_v = ((float)(y + dy)) / (gridSize - 1);
475                                                 ccgSubSurf_evaluatorFVarUV(ss,
476                                                                            index,
477                                                                            S,
478                                                                            grid_u, grid_v,
479                                                                            uv[i]);
480                                         }
481                                         if (tf) {
482                                                 copy_v2_v2(tf->uv[0], uv[0]);
483                                                 copy_v2_v2(tf->uv[1], uv[1]);
484                                                 copy_v2_v2(tf->uv[2], uv[2]);
485                                                 copy_v2_v2(tf->uv[3], uv[3]);
486                                                 tf++;
487                                         }
488                                         if (mluv) {
489                                                 copy_v2_v2(mluv[0].uv, uv[0]);
490                                                 copy_v2_v2(mluv[1].uv, uv[1]);
491                                                 copy_v2_v2(mluv[2].uv, uv[2]);
492                                                 copy_v2_v2(mluv[3].uv, uv[3]);
493                                                 mluv += 4;
494                                         }
495                                 }
496                         }
497                 }
498         }
499         MEM_freeN(faceMap);
500 }
501 #endif  /* WITH_OPENSUBDIV */
502
503 static void set_subsurf_legacy_uv(CCGSubSurf *ss, DerivedMesh *dm, DerivedMesh *result, int n)
504 {
505         CCGSubSurf *uvss;
506         CCGFace **faceMap;
507         MTFace *tf;
508         MLoopUV *mluv;
509         CCGFaceIterator fi;
510         int index, gridSize, gridFaces, /*edgeSize,*/ totface, x, y, S;
511         MLoopUV *dmloopuv = CustomData_get_layer_n(&dm->loopData, CD_MLOOPUV, n);
512         /* need to update both CD_MTFACE & CD_MLOOPUV, hrmf, we could get away with
513          * just tface except applying the modifier then looses subsurf UV */
514         MTFace *tface = CustomData_get_layer_n(&result->faceData, CD_MTFACE, n);
515         MLoopUV *mloopuv = CustomData_get_layer_n(&result->loopData, CD_MLOOPUV, n);
516
517         if (!dmloopuv || (!tface && !mloopuv))
518                 return;
519
520         /* create a CCGSubSurf from uv's */
521         uvss = _getSubSurf(NULL, ccgSubSurf_getSubdivisionLevels(ss), 2, CCG_USE_ARENA);
522
523         if (!ss_sync_from_uv(uvss, ss, dm, dmloopuv)) {
524                 ccgSubSurf_free(uvss);
525                 return;
526         }
527
528         /* get some info from CCGSubSurf */
529         totface = ccgSubSurf_getNumFaces(uvss);
530         /* edgeSize = ccgSubSurf_getEdgeSize(uvss); */ /*UNUSED*/
531         gridSize = ccgSubSurf_getGridSize(uvss);
532         gridFaces = gridSize - 1;
533
534         /* make a map from original faces to CCGFaces */
535         faceMap = MEM_mallocN(totface * sizeof(*faceMap), "facemapuv");
536         for (ccgSubSurf_initFaceIterator(uvss, &fi); !ccgFaceIterator_isStopped(&fi); ccgFaceIterator_next(&fi)) {
537                 CCGFace *f = ccgFaceIterator_getCurrent(&fi);
538                 faceMap[GET_INT_FROM_POINTER(ccgSubSurf_getFaceFaceHandle(f))] = f;
539         }
540
541         /* load coordinates from uvss into tface */
542         tf = tface;
543         mluv = mloopuv;
544
545         for (index = 0; index < totface; index++) {
546                 CCGFace *f = faceMap[index];
547                 int numVerts = ccgSubSurf_getFaceNumVerts(f);
548
549                 for (S = 0; S < numVerts; S++) {
550                         float (*faceGridData)[2] = ccgSubSurf_getFaceGridDataArray(uvss, f, S);
551
552                         for (y = 0; y < gridFaces; y++) {
553                                 for (x = 0; x < gridFaces; x++) {
554                                         float *a = faceGridData[(y + 0) * gridSize + x + 0];
555                                         float *b = faceGridData[(y + 0) * gridSize + x + 1];
556                                         float *c = faceGridData[(y + 1) * gridSize + x + 1];
557                                         float *d = faceGridData[(y + 1) * gridSize + x + 0];
558
559                                         if (tf) {
560                                                 copy_v2_v2(tf->uv[0], a);
561                                                 copy_v2_v2(tf->uv[1], d);
562                                                 copy_v2_v2(tf->uv[2], c);
563                                                 copy_v2_v2(tf->uv[3], b);
564                                                 tf++;
565                                         }
566
567                                         if (mluv) {
568                                                 copy_v2_v2(mluv[0].uv, a);
569                                                 copy_v2_v2(mluv[1].uv, d);
570                                                 copy_v2_v2(mluv[2].uv, c);
571                                                 copy_v2_v2(mluv[3].uv, b);
572                                                 mluv += 4;
573                                         }
574
575                                 }
576                         }
577                 }
578         }
579
580         ccgSubSurf_free(uvss);
581         MEM_freeN(faceMap);
582 }
583
584 static void set_subsurf_uv(CCGSubSurf *ss,
585                            DerivedMesh *dm,
586                            DerivedMesh *result,
587                            int layer_index)
588 {
589 #ifdef WITH_OPENSUBDIV
590         if (!ccgSubSurf_needGrids(ss)) {
591                 /* GPU backend is used, no need to evaluate UVs on CPU. */
592                 /* TODO(sergey): Think of how to support edit mode of UVs. */
593         }
594         else
595 #endif
596         {
597                 set_subsurf_legacy_uv(ss, dm, result, layer_index);
598         }
599 }
600
601 /* face weighting */
602 typedef struct FaceVertWeightEntry {
603         FaceVertWeight *weight;
604         float *w;
605         int valid;
606 } FaceVertWeightEntry;
607
608 typedef struct WeightTable {
609         FaceVertWeightEntry *weight_table;
610         int len;
611 } WeightTable;
612
613 static float *get_ss_weights(WeightTable *wtable, int gridCuts, int faceLen)
614 {
615         int x, y, i, j;
616         float *w, w1, w2, w4, fac, fac2, fx, fy;
617
618         if (wtable->len <= faceLen) {
619                 void *tmp = MEM_callocN(sizeof(FaceVertWeightEntry) * (faceLen + 1), "weight table alloc 2");
620                 
621                 if (wtable->len) {
622                         memcpy(tmp, wtable->weight_table, sizeof(FaceVertWeightEntry) * wtable->len);
623                         MEM_freeN(wtable->weight_table);
624                 }
625                 
626                 wtable->weight_table = tmp;
627                 wtable->len = faceLen + 1;
628         }
629
630         if (!wtable->weight_table[faceLen].valid) {
631                 wtable->weight_table[faceLen].valid = 1;
632                 wtable->weight_table[faceLen].w = w = MEM_callocN(sizeof(float) * faceLen * faceLen * (gridCuts + 2) * (gridCuts + 2), "weight table alloc");
633                 fac = 1.0f / (float)faceLen;
634
635                 for (i = 0; i < faceLen; i++) {
636                         for (x = 0; x < gridCuts + 2; x++) {
637                                 for (y = 0; y < gridCuts + 2; y++) {
638                                         fx = 0.5f - (float)x / (float)(gridCuts + 1) / 2.0f;
639                                         fy = 0.5f - (float)y / (float)(gridCuts + 1) / 2.0f;
640                                 
641                                         fac2 = faceLen - 4;
642                                         w1 = (1.0f - fx) * (1.0f - fy) + (-fac2 * fx * fy * fac);
643                                         w2 = (1.0f - fx + fac2 * fx * -fac) * (fy);
644                                         w4 = (fx) * (1.0f - fy + -fac2 * fy * fac);
645
646                                         /* these values aren't used for tri's and cause divide by zero */
647                                         if (faceLen > 3) {
648                                                 fac2 = 1.0f - (w1 + w2 + w4);
649                                                 fac2 = fac2 / (float)(faceLen - 3);
650                                                 for (j = 0; j < faceLen; j++) {
651                                                         w[j] = fac2;
652                                                 }
653                                         }
654                                         
655                                         w[i] = w1;
656                                         w[(i - 1 + faceLen) % faceLen] = w2;
657                                         w[(i + 1) % faceLen] = w4;
658
659                                         w += faceLen;
660                                 }
661                         }
662                 }
663         }
664
665         return wtable->weight_table[faceLen].w;
666 }
667
668 static void free_ss_weights(WeightTable *wtable)
669 {
670         int i;
671
672         for (i = 0; i < wtable->len; i++) {
673                 if (wtable->weight_table[i].valid)
674                         MEM_freeN(wtable->weight_table[i].w);
675         }
676         
677         if (wtable->weight_table)
678                 MEM_freeN(wtable->weight_table);
679 }
680
681 static void ss_sync_ccg_from_derivedmesh(CCGSubSurf *ss,
682                                          DerivedMesh *dm,
683                                          float (*vertexCos)[3],
684                                          int useFlatSubdiv)
685 {
686         float creaseFactor = (float) ccgSubSurf_getSubdivisionLevels(ss);
687 #ifndef USE_DYNSIZE
688         CCGVertHDL *fVerts = NULL;
689         BLI_array_declare(fVerts);
690 #endif
691         MVert *mvert = dm->getVertArray(dm);
692         MEdge *medge = dm->getEdgeArray(dm);
693         /* MFace *mface = dm->getTessFaceArray(dm); */ /* UNUSED */
694         MVert *mv;
695         MEdge *me;
696         MLoop *mloop = dm->getLoopArray(dm), *ml;
697         MPoly *mpoly = dm->getPolyArray(dm), *mp;
698         /*MFace *mf;*/ /*UNUSED*/
699         int totvert = dm->getNumVerts(dm);
700         int totedge = dm->getNumEdges(dm);
701         /*int totface = dm->getNumTessFaces(dm);*/ /*UNUSED*/
702         /*int totpoly = dm->getNumFaces(dm);*/ /*UNUSED*/
703         int i, j;
704         int *index;
705
706         ccgSubSurf_initFullSync(ss);
707
708         mv = mvert;
709         index = (int *)dm->getVertDataArray(dm, CD_ORIGINDEX);
710         for (i = 0; i < totvert; i++, mv++) {
711                 CCGVert *v;
712
713                 if (vertexCos) {
714                         ccgSubSurf_syncVert(ss, SET_INT_IN_POINTER(i), vertexCos[i], 0, &v);
715                 }
716                 else {
717                         ccgSubSurf_syncVert(ss, SET_INT_IN_POINTER(i), mv->co, 0, &v);
718                 }
719
720                 ((int *)ccgSubSurf_getVertUserData(ss, v))[1] = (index) ? *index++ : i;
721         }
722
723         me = medge;
724         index = (int *)dm->getEdgeDataArray(dm, CD_ORIGINDEX);
725         for (i = 0; i < totedge; i++, me++) {
726                 CCGEdge *e;
727                 float crease;
728
729                 crease = useFlatSubdiv ? creaseFactor :
730                          me->crease * creaseFactor / 255.0f;
731
732                 ccgSubSurf_syncEdge(ss, SET_INT_IN_POINTER(i), SET_UINT_IN_POINTER(me->v1),
733                                     SET_UINT_IN_POINTER(me->v2), crease, &e);
734
735                 ((int *)ccgSubSurf_getEdgeUserData(ss, e))[1] = (index) ? *index++ : i;
736         }
737
738         mp = mpoly;
739         index = (int *)dm->getPolyDataArray(dm, CD_ORIGINDEX);
740         for (i = 0; i < dm->numPolyData; i++, mp++) {
741                 CCGFace *f;
742
743 #ifdef USE_DYNSIZE
744                 CCGVertHDL fVerts[mp->totloop];
745 #else
746                 BLI_array_empty(fVerts);
747                 BLI_array_grow_items(fVerts, mp->totloop);
748 #endif
749
750                 ml = mloop + mp->loopstart;
751                 for (j = 0; j < mp->totloop; j++, ml++) {
752                         fVerts[j] = SET_UINT_IN_POINTER(ml->v);
753                 }
754
755                 /* this is very bad, means mesh is internally inconsistent.
756                  * it is not really possible to continue without modifying
757                  * other parts of code significantly to handle missing faces.
758                  * since this really shouldn't even be possible we just bail.*/
759                 if (ccgSubSurf_syncFace(ss, SET_INT_IN_POINTER(i), mp->totloop,
760                                         fVerts, &f) == eCCGError_InvalidValue)
761                 {
762                         static int hasGivenError = 0;
763
764                         if (!hasGivenError) {
765                                 //XXX error("Unrecoverable error in SubSurf calculation,"
766                                 //      " mesh is inconsistent.");
767
768                                 hasGivenError = 1;
769                         }
770
771                         return;
772                 }
773
774                 ((int *)ccgSubSurf_getFaceUserData(ss, f))[1] = (index) ? *index++ : i;
775         }
776
777         ccgSubSurf_processSync(ss);
778
779 #ifndef USE_DYNSIZE
780         BLI_array_free(fVerts);
781 #endif
782 }
783
784 #ifdef WITH_OPENSUBDIV
785 static void ss_sync_osd_from_derivedmesh(CCGSubSurf *ss,
786                                          DerivedMesh *dm)
787 {
788         ccgSubSurf_initFullSync(ss);
789         ccgSubSurf_prepareTopologyRefiner(ss, dm);
790         ccgSubSurf_processSync(ss);
791 }
792 #endif  /* WITH_OPENSUBDIV */
793
794 static void ss_sync_from_derivedmesh(CCGSubSurf *ss,
795                                      DerivedMesh *dm,
796                                      float (*vertexCos)[3],
797                                      int use_flat_subdiv,
798                                      bool use_subdiv_uvs)
799 {
800 #ifdef WITH_OPENSUBDIV
801         /* Reset all related descriptors if actual mesh topology changed or if
802          * other evaluation-related settings changed.
803          */
804         if (!ccgSubSurf_needGrids(ss)) {
805                 /* TODO(sergey): Use vertex coordinates and flat subdiv flag. */
806                 ccgSubSurf__sync_subdivUvs(ss, use_subdiv_uvs);
807                 ccgSubSurf_checkTopologyChanged(ss, dm);
808                 ss_sync_osd_from_derivedmesh(ss, dm);
809         }
810         else
811 #endif
812         {
813                 ss_sync_ccg_from_derivedmesh(ss, dm, vertexCos, use_flat_subdiv);
814         }
815 }
816
817 /***/
818
819 static int ccgDM_getVertMapIndex(CCGSubSurf *ss, CCGVert *v)
820 {
821         return ((int *) ccgSubSurf_getVertUserData(ss, v))[1];
822 }
823
824 static int ccgDM_getEdgeMapIndex(CCGSubSurf *ss, CCGEdge *e)
825 {
826         return ((int *) ccgSubSurf_getEdgeUserData(ss, e))[1];
827 }
828
829 static int ccgDM_getFaceMapIndex(CCGSubSurf *ss, CCGFace *f)
830 {
831         return ((int *) ccgSubSurf_getFaceUserData(ss, f))[1];
832 }
833
834 static void minmax_v3_v3v3(const float vec[3], float min[3], float max[3])
835 {
836         if (min[0] > vec[0]) min[0] = vec[0];
837         if (min[1] > vec[1]) min[1] = vec[1];
838         if (min[2] > vec[2]) min[2] = vec[2];
839         if (max[0] < vec[0]) max[0] = vec[0];
840         if (max[1] < vec[1]) max[1] = vec[1];
841         if (max[2] < vec[2]) max[2] = vec[2];
842 }
843
844 static void ccgDM_getMinMax(DerivedMesh *dm, float r_min[3], float r_max[3])
845 {
846         CCGDerivedMesh *ccgdm = (CCGDerivedMesh *) dm;
847         CCGSubSurf *ss = ccgdm->ss;
848         CCGVertIterator vi;
849         CCGEdgeIterator ei;
850         CCGFaceIterator fi;
851         CCGKey key;
852         int i, edgeSize = ccgSubSurf_getEdgeSize(ss);
853         int gridSize = ccgSubSurf_getGridSize(ss);
854
855 #ifdef WITH_OPENSUBDIV
856         if (ccgdm->useGpuBackend) {
857                 ccgSubSurf_getMinMax(ccgdm->ss, r_min, r_max);
858                 return;
859         }
860 #endif
861
862         CCG_key_top_level(&key, ss);
863
864         if (!ccgSubSurf_getNumVerts(ss))
865                 r_min[0] = r_min[1] = r_min[2] = r_max[0] = r_max[1] = r_max[2] = 0.0;
866
867         for (ccgSubSurf_initVertIterator(ss, &vi); !ccgVertIterator_isStopped(&vi); ccgVertIterator_next(&vi)) {
868                 CCGVert *v = ccgVertIterator_getCurrent(&vi);
869                 float *co = ccgSubSurf_getVertData(ss, v);
870
871                 minmax_v3_v3v3(co, r_min, r_max);
872         }
873
874         for (ccgSubSurf_initEdgeIterator(ss, &ei); !ccgEdgeIterator_isStopped(&ei); ccgEdgeIterator_next(&ei)) {
875                 CCGEdge *e = ccgEdgeIterator_getCurrent(&ei);
876                 CCGElem *edgeData = ccgSubSurf_getEdgeDataArray(ss, e);
877
878                 for (i = 0; i < edgeSize; i++)
879                         minmax_v3_v3v3(CCG_elem_offset_co(&key, edgeData, i), r_min, r_max);
880         }
881
882         for (ccgSubSurf_initFaceIterator(ss, &fi); !ccgFaceIterator_isStopped(&fi); ccgFaceIterator_next(&fi)) {
883                 CCGFace *f = ccgFaceIterator_getCurrent(&fi);
884                 int S, x, y, numVerts = ccgSubSurf_getFaceNumVerts(f);
885
886                 for (S = 0; S < numVerts; S++) {
887                         CCGElem *faceGridData = ccgSubSurf_getFaceGridDataArray(ss, f, S);
888
889                         for (y = 0; y < gridSize; y++)
890                                 for (x = 0; x < gridSize; x++)
891                                         minmax_v3_v3v3(CCG_grid_elem_co(&key, faceGridData, x, y), r_min, r_max);
892                 }
893         }
894 }
895
896 static int ccgDM_getNumVerts(DerivedMesh *dm)
897 {
898         CCGDerivedMesh *ccgdm = (CCGDerivedMesh *) dm;
899
900         return ccgSubSurf_getNumFinalVerts(ccgdm->ss);
901 }
902
903 static int ccgDM_getNumEdges(DerivedMesh *dm)
904 {
905         CCGDerivedMesh *ccgdm = (CCGDerivedMesh *) dm;
906
907         return ccgSubSurf_getNumFinalEdges(ccgdm->ss);
908 }
909
910 static int ccgDM_getNumPolys(DerivedMesh *dm)
911 {
912         CCGDerivedMesh *ccgdm = (CCGDerivedMesh *) dm;
913
914         return ccgSubSurf_getNumFinalFaces(ccgdm->ss);
915 }
916
917 static int ccgDM_getNumTessFaces(DerivedMesh *dm)
918 {
919         return dm->numTessFaceData;
920 }
921
922 static int ccgDM_getNumLoops(DerivedMesh *dm)
923 {
924         CCGDerivedMesh *ccgdm = (CCGDerivedMesh *) dm;
925
926         /* All subsurf faces are quads */
927         return 4 * ccgSubSurf_getNumFinalFaces(ccgdm->ss);
928 }
929
930 static void ccgDM_getFinalVert(DerivedMesh *dm, int vertNum, MVert *mv)
931 {
932         CCGDerivedMesh *ccgdm = (CCGDerivedMesh *) dm;
933         CCGSubSurf *ss = ccgdm->ss;
934         CCGElem *vd;
935         CCGKey key;
936         int i;
937
938         CCG_key_top_level(&key, ss);
939         memset(mv, 0, sizeof(*mv));
940
941         if ((vertNum < ccgdm->edgeMap[0].startVert) && (ccgSubSurf_getNumFaces(ss) > 0)) {
942                 /* this vert comes from face data */
943                 int lastface = ccgSubSurf_getNumFaces(ss) - 1;
944                 CCGFace *f;
945                 int x, y, grid, numVerts;
946                 int offset;
947                 int gridSize = ccgSubSurf_getGridSize(ss);
948                 int gridSideVerts;
949                 int gridInternalVerts;
950                 int gridSideEnd;
951                 int gridInternalEnd;
952
953                 i = 0;
954                 while (i < lastface && vertNum >= ccgdm->faceMap[i + 1].startVert) {
955                         i++;
956                 }
957
958                 f = ccgdm->faceMap[i].face;
959                 numVerts = ccgSubSurf_getFaceNumVerts(f);
960
961                 gridSideVerts = gridSize - 2;
962                 gridInternalVerts = gridSideVerts * gridSideVerts;
963
964                 gridSideEnd = 1 + numVerts * gridSideVerts;
965                 gridInternalEnd = gridSideEnd + numVerts * gridInternalVerts;
966
967                 offset = vertNum - ccgdm->faceMap[i].startVert;
968                 if (offset < 1) {
969                         vd = ccgSubSurf_getFaceCenterData(f);
970                         copy_v3_v3(mv->co, CCG_elem_co(&key, vd));
971                         normal_float_to_short_v3(mv->no, CCG_elem_no(&key, vd));
972                 }
973                 else if (offset < gridSideEnd) {
974                         offset -= 1;
975                         grid = offset / gridSideVerts;
976                         x = offset % gridSideVerts + 1;
977                         vd = ccgSubSurf_getFaceGridEdgeData(ss, f, grid, x);
978                         copy_v3_v3(mv->co, CCG_elem_co(&key, vd));
979                         normal_float_to_short_v3(mv->no, CCG_elem_no(&key, vd));
980                 }
981                 else if (offset < gridInternalEnd) {
982                         offset -= gridSideEnd;
983                         grid = offset / gridInternalVerts;
984                         offset %= gridInternalVerts;
985                         y = offset / gridSideVerts + 1;
986                         x = offset % gridSideVerts + 1;
987                         vd = ccgSubSurf_getFaceGridData(ss, f, grid, x, y);
988                         copy_v3_v3(mv->co, CCG_elem_co(&key, vd));
989                         normal_float_to_short_v3(mv->no, CCG_elem_no(&key, vd));
990                 }
991         }
992         else if ((vertNum < ccgdm->vertMap[0].startVert) && (ccgSubSurf_getNumEdges(ss) > 0)) {
993                 /* this vert comes from edge data */
994                 CCGEdge *e;
995                 int lastedge = ccgSubSurf_getNumEdges(ss) - 1;
996                 int x;
997
998                 i = 0;
999                 while (i < lastedge && vertNum >= ccgdm->edgeMap[i + 1].startVert) {
1000                         i++;
1001                 }
1002
1003                 e = ccgdm->edgeMap[i].edge;
1004
1005                 x = vertNum - ccgdm->edgeMap[i].startVert + 1;
1006                 vd = ccgSubSurf_getEdgeData(ss, e, x);
1007                 copy_v3_v3(mv->co, CCG_elem_co(&key, vd));
1008                 normal_float_to_short_v3(mv->no, CCG_elem_no(&key, vd));
1009         }
1010         else {
1011                 /* this vert comes from vert data */
1012                 CCGVert *v;
1013                 i = vertNum - ccgdm->vertMap[0].startVert;
1014
1015                 v = ccgdm->vertMap[i].vert;
1016                 vd = ccgSubSurf_getVertData(ss, v);
1017                 copy_v3_v3(mv->co, CCG_elem_co(&key, vd));
1018                 normal_float_to_short_v3(mv->no, CCG_elem_no(&key, vd));
1019         }
1020 }
1021
1022 static void ccgDM_getFinalVertCo(DerivedMesh *dm, int vertNum, float r_co[3])
1023 {
1024         MVert mvert;
1025
1026         ccgDM_getFinalVert(dm, vertNum, &mvert);
1027         copy_v3_v3(r_co, mvert.co);
1028 }
1029
1030 static void ccgDM_getFinalVertNo(DerivedMesh *dm, int vertNum, float r_no[3])
1031 {
1032         MVert mvert;
1033
1034         ccgDM_getFinalVert(dm, vertNum, &mvert);
1035         normal_short_to_float_v3(r_no, mvert.no);
1036 }
1037
1038 static void ccgDM_getFinalEdge(DerivedMesh *dm, int edgeNum, MEdge *med)
1039 {
1040         CCGDerivedMesh *ccgdm = (CCGDerivedMesh *) dm;
1041         CCGSubSurf *ss = ccgdm->ss;
1042         int i;
1043
1044         memset(med, 0, sizeof(*med));
1045
1046         if (edgeNum < ccgdm->edgeMap[0].startEdge) {
1047                 /* this edge comes from face data */
1048                 int lastface = ccgSubSurf_getNumFaces(ss) - 1;
1049                 CCGFace *f;
1050                 int x, y, grid /*, numVerts*/;
1051                 int offset;
1052                 int gridSize = ccgSubSurf_getGridSize(ss);
1053                 int edgeSize = ccgSubSurf_getEdgeSize(ss);
1054                 int gridSideEdges;
1055                 int gridInternalEdges;
1056
1057                 /* code added in bmesh but works correctly without, commenting - campbell */
1058 #if 0
1059                 int lasti, previ;
1060                 i = lastface;
1061                 lasti = 0;
1062                 while (1) {
1063                         previ = i;
1064                         if (ccgdm->faceMap[i].startEdge >= edgeNum) {
1065                                 i -= fabsf(i - lasti) / 2.0f;
1066                         }
1067                         else if (ccgdm->faceMap[i].startEdge < edgeNum) {
1068                                 i += fabsf(i - lasti) / 2.0f;
1069                         }
1070                         else {
1071                                 break;
1072                         }
1073
1074                         if (i < 0) {
1075                                 i = 0;
1076                                 break;
1077                         }
1078
1079                         if (i > lastface) {
1080                                 i = lastface;
1081                                 break;
1082
1083                         }
1084
1085                         if (i == lasti)
1086                                 break;
1087
1088                         lasti = previ;
1089                 }
1090
1091                 i = i > 0 ? i - 1 : i;
1092 #endif
1093
1094                 i = 0;
1095                 while (i < lastface && edgeNum >= ccgdm->faceMap[i + 1].startEdge) {
1096                         i++;
1097                 }
1098
1099                 f = ccgdm->faceMap[i].face;
1100                 /* numVerts = ccgSubSurf_getFaceNumVerts(f); */ /*UNUSED*/
1101
1102                 gridSideEdges = gridSize - 1;
1103                 gridInternalEdges = (gridSideEdges - 1) * gridSideEdges * 2; 
1104
1105                 offset = edgeNum - ccgdm->faceMap[i].startEdge;
1106                 grid = offset / (gridSideEdges + gridInternalEdges);
1107                 offset %= (gridSideEdges + gridInternalEdges);
1108
1109                 if (offset < gridSideEdges) {
1110                         x = offset;
1111                         med->v1 = getFaceIndex(ss, f, grid, x, 0, edgeSize, gridSize);
1112                         med->v2 = getFaceIndex(ss, f, grid, x + 1, 0, edgeSize, gridSize);
1113                 }
1114                 else {
1115                         offset -= gridSideEdges;
1116                         x = (offset / 2) / gridSideEdges + 1;
1117                         y = (offset / 2) % gridSideEdges;
1118                         if (offset % 2 == 0) {
1119                                 med->v1 = getFaceIndex(ss, f, grid, x, y, edgeSize, gridSize);
1120                                 med->v2 = getFaceIndex(ss, f, grid, x, y + 1, edgeSize, gridSize);
1121                         }
1122                         else {
1123                                 med->v1 = getFaceIndex(ss, f, grid, y, x, edgeSize, gridSize);
1124                                 med->v2 = getFaceIndex(ss, f, grid, y + 1, x, edgeSize, gridSize);
1125                         }
1126                 }
1127         }
1128         else {
1129                 /* this vert comes from edge data */
1130                 CCGEdge *e;
1131                 int edgeSize = ccgSubSurf_getEdgeSize(ss);
1132                 int x;
1133                 short *edgeFlag;
1134                 unsigned int flags = 0;
1135
1136                 i = (edgeNum - ccgdm->edgeMap[0].startEdge) / (edgeSize - 1);
1137
1138                 e = ccgdm->edgeMap[i].edge;
1139
1140                 if (!ccgSubSurf_getEdgeNumFaces(e)) flags |= ME_LOOSEEDGE;
1141
1142                 x = edgeNum - ccgdm->edgeMap[i].startEdge;
1143
1144                 med->v1 = getEdgeIndex(ss, e, x, edgeSize);
1145                 med->v2 = getEdgeIndex(ss, e, x + 1, edgeSize);
1146
1147                 edgeFlag = (ccgdm->edgeFlags) ? &ccgdm->edgeFlags[i] : NULL;
1148                 if (edgeFlag)
1149                         flags |= (*edgeFlag & (ME_SEAM | ME_SHARP)) | ME_EDGEDRAW | ME_EDGERENDER;
1150                 else
1151                         flags |= ME_EDGEDRAW | ME_EDGERENDER;
1152
1153                 med->flag = flags;
1154         }
1155 }
1156
1157 static void ccgDM_getFinalFace(DerivedMesh *dm, int faceNum, MFace *mf)
1158 {
1159         CCGDerivedMesh *ccgdm = (CCGDerivedMesh *) dm;
1160         CCGSubSurf *ss = ccgdm->ss;
1161         int gridSize = ccgSubSurf_getGridSize(ss);
1162         int edgeSize = ccgSubSurf_getEdgeSize(ss);
1163         int gridSideEdges = gridSize - 1;
1164         int gridFaces = gridSideEdges * gridSideEdges;
1165         int i;
1166         CCGFace *f;
1167         /*int numVerts;*/
1168         int offset;
1169         int grid;
1170         int x, y;
1171         /*int lastface = ccgSubSurf_getNumFaces(ss) - 1;*/ /*UNUSED*/
1172         DMFlagMat *faceFlags = ccgdm->faceFlags;
1173
1174         memset(mf, 0, sizeof(*mf));
1175         if (faceNum >= ccgdm->dm.numTessFaceData)
1176                 return;
1177
1178         i = ccgdm->reverseFaceMap[faceNum];
1179
1180         f = ccgdm->faceMap[i].face;
1181         /*numVerts = ccgSubSurf_getFaceNumVerts(f);*/ /*UNUSED*/
1182
1183         offset = faceNum - ccgdm->faceMap[i].startFace;
1184         grid = offset / gridFaces;
1185         offset %= gridFaces;
1186         y = offset / gridSideEdges;
1187         x = offset % gridSideEdges;
1188
1189         mf->v1 = getFaceIndex(ss, f, grid, x + 0, y + 0, edgeSize, gridSize);
1190         mf->v2 = getFaceIndex(ss, f, grid, x + 0, y + 1, edgeSize, gridSize);
1191         mf->v3 = getFaceIndex(ss, f, grid, x + 1, y + 1, edgeSize, gridSize);
1192         mf->v4 = getFaceIndex(ss, f, grid, x + 1, y + 0, edgeSize, gridSize);
1193
1194         if (faceFlags) {
1195                 mf->flag = faceFlags[i].flag;
1196                 mf->mat_nr = faceFlags[i].mat_nr;
1197         }
1198         else {
1199                 mf->flag = ME_SMOOTH;
1200         }
1201
1202         mf->edcode = 0;
1203 }
1204
1205 /* Translate GridHidden into the ME_HIDE flag for MVerts. Assumes
1206  * vertices are in the order output by ccgDM_copyFinalVertArray. */
1207 void subsurf_copy_grid_hidden(DerivedMesh *dm, const MPoly *mpoly,
1208                               MVert *mvert, const MDisps *mdisps)
1209 {
1210         CCGDerivedMesh *ccgdm = (CCGDerivedMesh *)dm;
1211         CCGSubSurf *ss = ccgdm->ss;
1212         int level = ccgSubSurf_getSubdivisionLevels(ss);
1213         int gridSize = ccgSubSurf_getGridSize(ss);
1214         int edgeSize = ccgSubSurf_getEdgeSize(ss);
1215         int totface = ccgSubSurf_getNumFaces(ss);
1216         int i, j, x, y;
1217         
1218         for (i = 0; i < totface; i++) {
1219                 CCGFace *f = ccgdm->faceMap[i].face;
1220
1221                 for (j = 0; j < mpoly[i].totloop; j++) {
1222                         const MDisps *md = &mdisps[mpoly[i].loopstart + j];
1223                         int hidden_gridsize = BKE_ccg_gridsize(md->level);
1224                         int factor = BKE_ccg_factor(level, md->level);
1225                         BLI_bitmap *hidden = md->hidden;
1226                         
1227                         if (!hidden)
1228                                 continue;
1229                         
1230                         for (y = 0; y < gridSize; y++) {
1231                                 for (x = 0; x < gridSize; x++) {
1232                                         int vndx, offset;
1233                                         
1234                                         vndx = getFaceIndex(ss, f, j, x, y, edgeSize, gridSize);
1235                                         offset = (y * factor) * hidden_gridsize + (x * factor);
1236                                         if (BLI_BITMAP_TEST(hidden, offset))
1237                                                 mvert[vndx].flag |= ME_HIDE;
1238                                 }
1239                         }
1240                 }
1241         }
1242 }
1243
1244 /* Translate GridPaintMask into vertex paint masks. Assumes vertices
1245  * are in the order output by ccgDM_copyFinalVertArray. */
1246 void subsurf_copy_grid_paint_mask(DerivedMesh *dm, const MPoly *mpoly,
1247                                   float *paint_mask,
1248                                   const GridPaintMask *grid_paint_mask)
1249 {
1250         CCGDerivedMesh *ccgdm = (CCGDerivedMesh *)dm;
1251         CCGSubSurf *ss = ccgdm->ss;
1252         int level = ccgSubSurf_getSubdivisionLevels(ss);
1253         int gridSize = ccgSubSurf_getGridSize(ss);
1254         int edgeSize = ccgSubSurf_getEdgeSize(ss);
1255         int totface = ccgSubSurf_getNumFaces(ss);
1256         int i, j, x, y, factor, gpm_gridsize;
1257         
1258         for (i = 0; i < totface; i++) {
1259                 CCGFace *f = ccgdm->faceMap[i].face;
1260                 const MPoly *p = &mpoly[i];
1261                 
1262                 for (j = 0; j < p->totloop; j++) {
1263                         const GridPaintMask *gpm = &grid_paint_mask[p->loopstart + j];
1264                         if (!gpm->data)
1265                                 continue;
1266
1267                         factor = BKE_ccg_factor(level, gpm->level);
1268                         gpm_gridsize = BKE_ccg_gridsize(gpm->level);
1269                         
1270                         for (y = 0; y < gridSize; y++) {
1271                                 for (x = 0; x < gridSize; x++) {
1272                                         int vndx, offset;
1273                                         
1274                                         vndx = getFaceIndex(ss, f, j, x, y, edgeSize, gridSize);
1275                                         offset = y * factor * gpm_gridsize + x * factor;
1276                                         paint_mask[vndx] = gpm->data[offset];
1277                                 }
1278                         }
1279                 }
1280         }
1281 }
1282
1283 /* utility functon */
1284 BLI_INLINE void ccgDM_to_MVert(MVert *mv, const CCGKey *key, CCGElem *elem)
1285 {
1286         copy_v3_v3(mv->co, CCG_elem_co(key, elem));
1287         normal_float_to_short_v3(mv->no, CCG_elem_no(key, elem));
1288         mv->flag = mv->bweight = 0;
1289 }
1290
1291 static void ccgDM_copyFinalVertArray(DerivedMesh *dm, MVert *mvert)
1292 {
1293         CCGDerivedMesh *ccgdm = (CCGDerivedMesh *) dm;
1294         CCGSubSurf *ss = ccgdm->ss;
1295         CCGElem *vd;
1296         CCGKey key;
1297         int index;
1298         int totvert, totedge, totface;
1299         int gridSize = ccgSubSurf_getGridSize(ss);
1300         int edgeSize = ccgSubSurf_getEdgeSize(ss);
1301         unsigned int i = 0;
1302
1303         CCG_key_top_level(&key, ss);
1304
1305         totface = ccgSubSurf_getNumFaces(ss);
1306         for (index = 0; index < totface; index++) {
1307                 CCGFace *f = ccgdm->faceMap[index].face;
1308                 int x, y, S, numVerts = ccgSubSurf_getFaceNumVerts(f);
1309
1310                 vd = ccgSubSurf_getFaceCenterData(f);
1311                 ccgDM_to_MVert(&mvert[i++], &key, vd);
1312                 
1313                 for (S = 0; S < numVerts; S++) {
1314                         for (x = 1; x < gridSize - 1; x++) {
1315                                 vd = ccgSubSurf_getFaceGridEdgeData(ss, f, S, x);
1316                                 ccgDM_to_MVert(&mvert[i++], &key, vd);
1317                         }
1318                 }
1319
1320                 for (S = 0; S < numVerts; S++) {
1321                         for (y = 1; y < gridSize - 1; y++) {
1322                                 for (x = 1; x < gridSize - 1; x++) {
1323                                         vd = ccgSubSurf_getFaceGridData(ss, f, S, x, y);
1324                                         ccgDM_to_MVert(&mvert[i++], &key, vd);
1325                                 }
1326                         }
1327                 }
1328         }
1329
1330         totedge = ccgSubSurf_getNumEdges(ss);
1331         for (index = 0; index < totedge; index++) {
1332                 CCGEdge *e = ccgdm->edgeMap[index].edge;
1333                 int x;
1334
1335                 for (x = 1; x < edgeSize - 1; x++) {
1336                         /* This gives errors with -debug-fpe
1337                          * the normals don't seem to be unit length.
1338                          * this is most likely caused by edges with no
1339                          * faces which are now zerod out, see comment in:
1340                          * ccgSubSurf__calcVertNormals(), - campbell */
1341                         vd = ccgSubSurf_getEdgeData(ss, e, x);
1342                         ccgDM_to_MVert(&mvert[i++], &key, vd);
1343                 }
1344         }
1345
1346         totvert = ccgSubSurf_getNumVerts(ss);
1347         for (index = 0; index < totvert; index++) {
1348                 CCGVert *v = ccgdm->vertMap[index].vert;
1349
1350                 vd = ccgSubSurf_getVertData(ss, v);
1351                 ccgDM_to_MVert(&mvert[i++], &key, vd);
1352         }
1353 }
1354
1355
1356 /* utility functon */
1357 BLI_INLINE void ccgDM_to_MEdge(MEdge *med, const int v1, const int v2, const short flag)
1358 {
1359         med->v1 = v1;
1360         med->v2 = v2;
1361         med->crease = med->bweight = 0;
1362         med->flag = flag;
1363 }
1364
1365 static void ccgDM_copyFinalEdgeArray(DerivedMesh *dm, MEdge *medge)
1366 {
1367         CCGDerivedMesh *ccgdm = (CCGDerivedMesh *) dm;
1368         CCGSubSurf *ss = ccgdm->ss;
1369         int index;
1370         int totedge, totface;
1371         int gridSize = ccgSubSurf_getGridSize(ss);
1372         int edgeSize = ccgSubSurf_getEdgeSize(ss);
1373         unsigned int i = 0;
1374         short *edgeFlags = ccgdm->edgeFlags;
1375         const short ed_interior_flag = ccgdm->drawInteriorEdges ? (ME_EDGEDRAW | ME_EDGERENDER) : 0;
1376
1377         totface = ccgSubSurf_getNumFaces(ss);
1378         for (index = 0; index < totface; index++) {
1379                 CCGFace *f = ccgdm->faceMap[index].face;
1380                 int x, y, S, numVerts = ccgSubSurf_getFaceNumVerts(f);
1381
1382                 for (S = 0; S < numVerts; S++) {
1383                         for (x = 0; x < gridSize - 1; x++) {
1384                                 ccgDM_to_MEdge(&medge[i++],
1385                                                getFaceIndex(ss, f, S, x,     0, edgeSize, gridSize),
1386                                                getFaceIndex(ss, f, S, x + 1, 0, edgeSize, gridSize),
1387                                                ed_interior_flag);
1388                         }
1389
1390                         for (x = 1; x < gridSize - 1; x++) {
1391                                 for (y = 0; y < gridSize - 1; y++) {
1392                                         ccgDM_to_MEdge(&medge[i++],
1393                                                        getFaceIndex(ss, f, S, x, y,    edgeSize, gridSize),
1394                                                        getFaceIndex(ss, f, S, x, y + 1, edgeSize, gridSize),
1395                                                        ed_interior_flag);
1396                                         ccgDM_to_MEdge(&medge[i++],
1397                                                        getFaceIndex(ss, f, S, y, x,     edgeSize, gridSize),
1398                                                        getFaceIndex(ss, f, S, y + 1, x, edgeSize, gridSize),
1399                                                        ed_interior_flag);
1400                                 }
1401                         }
1402                 }
1403         }
1404
1405         totedge = ccgSubSurf_getNumEdges(ss);
1406         for (index = 0; index < totedge; index++) {
1407                 CCGEdge *e = ccgdm->edgeMap[index].edge;
1408                 short ed_flag = 0;
1409                 int x;
1410                 int edgeIdx = GET_INT_FROM_POINTER(ccgSubSurf_getEdgeEdgeHandle(e));
1411
1412                 if (!ccgSubSurf_getEdgeNumFaces(e)) {
1413                         ed_flag |= ME_LOOSEEDGE;
1414                 }
1415
1416                 if (edgeFlags) {
1417                         if (edgeIdx != -1) {
1418                                 ed_flag |= ((edgeFlags[index] & (ME_SEAM | ME_SHARP)) | ME_EDGEDRAW | ME_EDGERENDER);
1419                         }
1420                 }
1421                 else {
1422                         ed_flag |= ME_EDGEDRAW | ME_EDGERENDER;
1423                 }
1424
1425                 for (x = 0; x < edgeSize - 1; x++) {
1426                         ccgDM_to_MEdge(&medge[i++],
1427                                        getEdgeIndex(ss, e, x, edgeSize),
1428                                        getEdgeIndex(ss, e, x + 1, edgeSize),
1429                                        ed_flag);
1430                 }
1431         }
1432 }
1433
1434 static void ccgDM_copyFinalFaceArray(DerivedMesh *dm, MFace *mface)
1435 {
1436         CCGDerivedMesh *ccgdm = (CCGDerivedMesh *) dm;
1437         CCGSubSurf *ss = ccgdm->ss;
1438         int index;
1439         int totface;
1440         int gridSize = ccgSubSurf_getGridSize(ss);
1441         int edgeSize = ccgSubSurf_getEdgeSize(ss);
1442         int i = 0;
1443         DMFlagMat *faceFlags = ccgdm->faceFlags;
1444
1445         totface = dm->getNumTessFaces(dm);
1446         for (index = 0; index < totface; index++) {
1447                 CCGFace *f = ccgdm->faceMap[index].face;
1448                 int x, y, S, numVerts = ccgSubSurf_getFaceNumVerts(f);
1449                 /* keep types in sync with MFace, avoid many conversions */
1450                 char flag = (faceFlags) ? faceFlags[index].flag : ME_SMOOTH;
1451                 short mat_nr = (faceFlags) ? faceFlags[index].mat_nr : 0;
1452
1453                 for (S = 0; S < numVerts; S++) {
1454                         for (y = 0; y < gridSize - 1; y++) {
1455                                 for (x = 0; x < gridSize - 1; x++) {
1456                                         MFace *mf = &mface[i];
1457                                         mf->v1 = getFaceIndex(ss, f, S, x + 0, y + 0,
1458                                                               edgeSize, gridSize);
1459                                         mf->v2 = getFaceIndex(ss, f, S, x + 0, y + 1,
1460                                                               edgeSize, gridSize);
1461                                         mf->v3 = getFaceIndex(ss, f, S, x + 1, y + 1,
1462                                                               edgeSize, gridSize);
1463                                         mf->v4 = getFaceIndex(ss, f, S, x + 1, y + 0,
1464                                                               edgeSize, gridSize);
1465                                         mf->mat_nr = mat_nr;
1466                                         mf->flag = flag;
1467                                         mf->edcode = 0;
1468
1469                                         i++;
1470                                 }
1471                         }
1472                 }
1473         }
1474 }
1475
1476 static void ccgDM_copyFinalLoopArray(DerivedMesh *dm, MLoop *mloop)
1477 {
1478         CCGDerivedMesh *ccgdm = (CCGDerivedMesh *) dm;
1479         CCGSubSurf *ss = ccgdm->ss;
1480         int index;
1481         int totface;
1482         int gridSize = ccgSubSurf_getGridSize(ss);
1483         int edgeSize = ccgSubSurf_getEdgeSize(ss);
1484         int i = 0;
1485         MLoop *mv;
1486         /* DMFlagMat *faceFlags = ccgdm->faceFlags; */ /* UNUSED */
1487
1488         if (!ccgdm->ehash) {
1489                 BLI_rw_mutex_lock(&loops_cache_rwlock, THREAD_LOCK_WRITE);
1490                 if (!ccgdm->ehash) {
1491                         MEdge *medge;
1492
1493                         ccgdm->ehash = BLI_edgehash_new_ex(__func__, ccgdm->dm.numEdgeData);
1494                         medge = ccgdm->dm.getEdgeArray((DerivedMesh *)ccgdm);
1495
1496                         for (i = 0; i < ccgdm->dm.numEdgeData; i++) {
1497                                 BLI_edgehash_insert(ccgdm->ehash, medge[i].v1, medge[i].v2, SET_INT_IN_POINTER(i));
1498                         }
1499                 }
1500                 BLI_rw_mutex_unlock(&loops_cache_rwlock);
1501         }
1502
1503         BLI_rw_mutex_lock(&loops_cache_rwlock, THREAD_LOCK_READ);
1504         totface = ccgSubSurf_getNumFaces(ss);
1505         mv = mloop;
1506         for (index = 0; index < totface; index++) {
1507                 CCGFace *f = ccgdm->faceMap[index].face;
1508                 int x, y, S, numVerts = ccgSubSurf_getFaceNumVerts(f);
1509                 /* int flag = (faceFlags) ? faceFlags[index * 2]: ME_SMOOTH; */ /* UNUSED */
1510                 /* int mat_nr = (faceFlags) ? faceFlags[index * 2 + 1]: 0; */ /* UNUSED */
1511
1512                 for (S = 0; S < numVerts; S++) {
1513                         for (y = 0; y < gridSize - 1; y++) {
1514                                 for (x = 0; x < gridSize - 1; x++) {
1515                                         unsigned int v1, v2, v3, v4;
1516
1517                                         v1 = getFaceIndex(ss, f, S, x + 0, y + 0,
1518                                                           edgeSize, gridSize);
1519
1520                                         v2 = getFaceIndex(ss, f, S, x + 0, y + 1,
1521                                                           edgeSize, gridSize);
1522                                         v3 = getFaceIndex(ss, f, S, x + 1, y + 1,
1523                                                           edgeSize, gridSize);
1524                                         v4 = getFaceIndex(ss, f, S, x + 1, y + 0,
1525                                                           edgeSize, gridSize);
1526
1527                                         mv->v = v1;
1528                                         mv->e = GET_UINT_FROM_POINTER(BLI_edgehash_lookup(ccgdm->ehash, v1, v2));
1529                                         mv++; i++;
1530
1531                                         mv->v = v2;
1532                                         mv->e = GET_UINT_FROM_POINTER(BLI_edgehash_lookup(ccgdm->ehash, v2, v3));
1533                                         mv++; i++;
1534
1535                                         mv->v = v3;
1536                                         mv->e = GET_UINT_FROM_POINTER(BLI_edgehash_lookup(ccgdm->ehash, v3, v4));
1537                                         mv++; i++;
1538
1539                                         mv->v = v4;
1540                                         mv->e = GET_UINT_FROM_POINTER(BLI_edgehash_lookup(ccgdm->ehash, v4, v1));
1541                                         mv++; i++;
1542                                 }
1543                         }
1544                 }
1545         }
1546         BLI_rw_mutex_unlock(&loops_cache_rwlock);
1547 }
1548
1549 static void ccgDM_copyFinalPolyArray(DerivedMesh *dm, MPoly *mpoly)
1550 {
1551         CCGDerivedMesh *ccgdm = (CCGDerivedMesh *) dm;
1552         CCGSubSurf *ss = ccgdm->ss;
1553         int index;
1554         int totface;
1555         int gridSize = ccgSubSurf_getGridSize(ss);
1556         /* int edgeSize = ccgSubSurf_getEdgeSize(ss); */ /* UNUSED */
1557         int i = 0, k = 0;
1558         DMFlagMat *faceFlags = ccgdm->faceFlags;
1559
1560         totface = ccgSubSurf_getNumFaces(ss);
1561         for (index = 0; index < totface; index++) {
1562                 CCGFace *f = ccgdm->faceMap[index].face;
1563                 int x, y, S, numVerts = ccgSubSurf_getFaceNumVerts(f);
1564                 int flag = (faceFlags) ? faceFlags[index].flag : ME_SMOOTH;
1565                 int mat_nr = (faceFlags) ? faceFlags[index].mat_nr : 0;
1566
1567                 for (S = 0; S < numVerts; S++) {
1568                         for (y = 0; y < gridSize - 1; y++) {
1569                                 for (x = 0; x < gridSize - 1; x++) {
1570                                         MPoly *mp = &mpoly[i];
1571
1572                                         mp->mat_nr = mat_nr;
1573                                         mp->flag = flag;
1574                                         mp->loopstart = k;
1575                                         mp->totloop = 4;
1576
1577                                         k += 4;
1578                                         i++;
1579                                 }
1580                         }
1581                 }
1582         }
1583 }
1584
1585 static void ccgdm_getVertCos(DerivedMesh *dm, float (*cos)[3])
1586 {
1587         CCGDerivedMesh *ccgdm = (CCGDerivedMesh *) dm;
1588         CCGSubSurf *ss = ccgdm->ss;
1589         int edgeSize = ccgSubSurf_getEdgeSize(ss);
1590         int gridSize = ccgSubSurf_getGridSize(ss);
1591         int i;
1592         CCGVertIterator vi;
1593         CCGEdgeIterator ei;
1594         CCGFaceIterator fi;
1595         CCGFace **faceMap2;
1596         CCGEdge **edgeMap2;
1597         CCGVert **vertMap2;
1598         int index, totvert, totedge, totface;
1599         
1600         totvert = ccgSubSurf_getNumVerts(ss);
1601         vertMap2 = MEM_mallocN(totvert * sizeof(*vertMap2), "vertmap");
1602         for (ccgSubSurf_initVertIterator(ss, &vi); !ccgVertIterator_isStopped(&vi); ccgVertIterator_next(&vi)) {
1603                 CCGVert *v = ccgVertIterator_getCurrent(&vi);
1604
1605                 vertMap2[GET_INT_FROM_POINTER(ccgSubSurf_getVertVertHandle(v))] = v;
1606         }
1607
1608         totedge = ccgSubSurf_getNumEdges(ss);
1609         edgeMap2 = MEM_mallocN(totedge * sizeof(*edgeMap2), "edgemap");
1610         for (ccgSubSurf_initEdgeIterator(ss, &ei), i = 0; !ccgEdgeIterator_isStopped(&ei); i++, ccgEdgeIterator_next(&ei)) {
1611                 CCGEdge *e = ccgEdgeIterator_getCurrent(&ei);
1612
1613                 edgeMap2[GET_INT_FROM_POINTER(ccgSubSurf_getEdgeEdgeHandle(e))] = e;
1614         }
1615
1616         totface = ccgSubSurf_getNumFaces(ss);
1617         faceMap2 = MEM_mallocN(totface * sizeof(*faceMap2), "facemap");
1618         for (ccgSubSurf_initFaceIterator(ss, &fi); !ccgFaceIterator_isStopped(&fi); ccgFaceIterator_next(&fi)) {
1619                 CCGFace *f = ccgFaceIterator_getCurrent(&fi);
1620
1621                 faceMap2[GET_INT_FROM_POINTER(ccgSubSurf_getFaceFaceHandle(f))] = f;
1622         }
1623
1624         i = 0;
1625         for (index = 0; index < totface; index++) {
1626                 CCGFace *f = faceMap2[index];
1627                 int x, y, S, numVerts = ccgSubSurf_getFaceNumVerts(f);
1628
1629                 copy_v3_v3(cos[i++], ccgSubSurf_getFaceCenterData(f));
1630                 
1631                 for (S = 0; S < numVerts; S++) {
1632                         for (x = 1; x < gridSize - 1; x++) {
1633                                 copy_v3_v3(cos[i++], ccgSubSurf_getFaceGridEdgeData(ss, f, S, x));
1634                         }
1635                 }
1636
1637                 for (S = 0; S < numVerts; S++) {
1638                         for (y = 1; y < gridSize - 1; y++) {
1639                                 for (x = 1; x < gridSize - 1; x++) {
1640                                         copy_v3_v3(cos[i++], ccgSubSurf_getFaceGridData(ss, f, S, x, y));
1641                                 }
1642                         }
1643                 }
1644         }
1645
1646         for (index = 0; index < totedge; index++) {
1647                 CCGEdge *e = edgeMap2[index];
1648                 int x;
1649
1650                 for (x = 1; x < edgeSize - 1; x++) {
1651                         copy_v3_v3(cos[i++], ccgSubSurf_getEdgeData(ss, e, x));
1652                 }
1653         }
1654
1655         for (index = 0; index < totvert; index++) {
1656                 CCGVert *v = vertMap2[index];
1657                 copy_v3_v3(cos[i++], ccgSubSurf_getVertData(ss, v));
1658         }
1659
1660         MEM_freeN(vertMap2);
1661         MEM_freeN(edgeMap2);
1662         MEM_freeN(faceMap2);
1663 }
1664
1665 static void ccgDM_foreachMappedVert(
1666         DerivedMesh *dm,
1667         void (*func)(void *userData, int index, const float co[3], const float no_f[3], const short no_s[3]),
1668         void *userData,
1669         DMForeachFlag flag)
1670 {
1671         CCGDerivedMesh *ccgdm = (CCGDerivedMesh *) dm;
1672         CCGVertIterator vi;
1673         CCGKey key;
1674         CCG_key_top_level(&key, ccgdm->ss);
1675
1676         for (ccgSubSurf_initVertIterator(ccgdm->ss, &vi); !ccgVertIterator_isStopped(&vi); ccgVertIterator_next(&vi)) {
1677                 CCGVert *v = ccgVertIterator_getCurrent(&vi);
1678                 const int index = ccgDM_getVertMapIndex(ccgdm->ss, v);
1679
1680                 if (index != -1) {
1681                         CCGElem *vd = ccgSubSurf_getVertData(ccgdm->ss, v);
1682                         const float *no = (flag & DM_FOREACH_USE_NORMAL) ? CCG_elem_no(&key, vd) : NULL;
1683                         func(userData, index, CCG_elem_co(&key, vd), no, NULL);
1684                 }
1685         }
1686 }
1687
1688 static void ccgDM_foreachMappedEdge(
1689         DerivedMesh *dm,
1690         void (*func)(void *userData, int index, const float v0co[3], const float v1co[3]),
1691         void *userData)
1692 {
1693         CCGDerivedMesh *ccgdm = (CCGDerivedMesh *) dm;
1694         CCGSubSurf *ss = ccgdm->ss;
1695         CCGEdgeIterator ei;
1696         CCGKey key;
1697         int i, edgeSize = ccgSubSurf_getEdgeSize(ss);
1698
1699         CCG_key_top_level(&key, ss);
1700
1701         for (ccgSubSurf_initEdgeIterator(ss, &ei); !ccgEdgeIterator_isStopped(&ei); ccgEdgeIterator_next(&ei)) {
1702                 CCGEdge *e = ccgEdgeIterator_getCurrent(&ei);
1703                 const int index = ccgDM_getEdgeMapIndex(ss, e);
1704
1705                 if (index != -1) {
1706                         CCGElem *edgeData = ccgSubSurf_getEdgeDataArray(ss, e);
1707                         for (i = 0; i < edgeSize - 1; i++) {
1708                                 func(userData, index, CCG_elem_offset_co(&key, edgeData, i), CCG_elem_offset_co(&key, edgeData, i + 1));
1709                         }
1710                 }
1711         }
1712 }
1713
1714 static void ccgDM_foreachMappedLoop(
1715         DerivedMesh *dm,
1716         void (*func)(void *userData, int vertex_index, int face_index, const float co[3], const float no[3]),
1717         void *userData,
1718         DMForeachFlag flag)
1719 {
1720         /* We can't use dm->getLoopDataLayout(dm) here, we want to always access dm->loopData, EditDerivedBMesh would
1721          * return loop data from bmesh itself. */
1722         const float (*lnors)[3] = (flag & DM_FOREACH_USE_NORMAL) ? DM_get_loop_data_layer(dm, CD_NORMAL) : NULL;
1723
1724         MVert *mv = dm->getVertArray(dm);
1725         MLoop *ml = dm->getLoopArray(dm);
1726         MPoly *mp = dm->getPolyArray(dm);
1727         const int *v_index = dm->getVertDataArray(dm, CD_ORIGINDEX);
1728         const int *f_index = dm->getPolyDataArray(dm, CD_ORIGINDEX);
1729         int p_idx, i;
1730
1731         for (p_idx = 0; p_idx < dm->numPolyData; ++p_idx, ++mp) {
1732                 for (i = 0; i < mp->totloop; ++i, ++ml) {
1733                         const int v_idx = v_index ? v_index[ml->v] : ml->v;
1734                         const int f_idx = f_index ? f_index[p_idx] : p_idx;
1735                         const float *no = lnors ? *lnors++ : NULL;
1736                         if (!ELEM(ORIGINDEX_NONE, v_idx, f_idx)) {
1737                                 func(userData, v_idx, f_idx, mv[ml->v].co, no);
1738                         }
1739                 }
1740         }
1741 }
1742
1743 static void ccgDM_drawVerts(DerivedMesh *dm)
1744 {
1745         CCGDerivedMesh *ccgdm = (CCGDerivedMesh *) dm;
1746         CCGSubSurf *ss = ccgdm->ss;
1747         int edgeSize = ccgSubSurf_getEdgeSize(ss);
1748         int gridSize = ccgSubSurf_getGridSize(ss);
1749         CCGVertIterator vi;
1750         CCGEdgeIterator ei;
1751         CCGFaceIterator fi;
1752
1753         glBegin(GL_POINTS);
1754         for (ccgSubSurf_initVertIterator(ss, &vi); !ccgVertIterator_isStopped(&vi); ccgVertIterator_next(&vi)) {
1755                 CCGVert *v = ccgVertIterator_getCurrent(&vi);
1756                 glVertex3fv(ccgSubSurf_getVertData(ss, v));
1757         }
1758
1759         for (ccgSubSurf_initEdgeIterator(ss, &ei); !ccgEdgeIterator_isStopped(&ei); ccgEdgeIterator_next(&ei)) {
1760                 CCGEdge *e = ccgEdgeIterator_getCurrent(&ei);
1761                 int x;
1762
1763                 for (x = 1; x < edgeSize - 1; x++)
1764                         glVertex3fv(ccgSubSurf_getEdgeData(ss, e, x));
1765         }
1766
1767         for (ccgSubSurf_initFaceIterator(ss, &fi); !ccgFaceIterator_isStopped(&fi); ccgFaceIterator_next(&fi)) {
1768                 CCGFace *f = ccgFaceIterator_getCurrent(&fi);
1769                 int x, y, S, numVerts = ccgSubSurf_getFaceNumVerts(f);
1770
1771                 glVertex3fv(ccgSubSurf_getFaceCenterData(f));
1772                 for (S = 0; S < numVerts; S++)
1773                         for (x = 1; x < gridSize - 1; x++)
1774                                 glVertex3fv(ccgSubSurf_getFaceGridEdgeData(ss, f, S, x));
1775                 for (S = 0; S < numVerts; S++)
1776                         for (y = 1; y < gridSize - 1; y++)
1777                                 for (x = 1; x < gridSize - 1; x++)
1778                                         glVertex3fv(ccgSubSurf_getFaceGridData(ss, f, S, x, y));
1779         }
1780         glEnd();
1781 }
1782
1783 static void ccgdm_pbvh_update(CCGDerivedMesh *ccgdm)
1784 {
1785         if (ccgdm->pbvh && ccgDM_use_grid_pbvh(ccgdm)) {
1786                 CCGFace **faces;
1787                 int totface;
1788
1789                 BKE_pbvh_get_grid_updates(ccgdm->pbvh, 1, (void ***)&faces, &totface);
1790                 if (totface) {
1791                         ccgSubSurf_updateFromFaces(ccgdm->ss, 0, faces, totface);
1792                         ccgSubSurf_updateNormals(ccgdm->ss, faces, totface);
1793                         MEM_freeN(faces);
1794                 }
1795         }
1796 }
1797
1798 static void ccgDM_drawEdges(DerivedMesh *dm, bool drawLooseEdges, bool drawAllEdges)
1799 {
1800         GPUDrawObject *gdo;
1801         CCGDerivedMesh *ccgdm = (CCGDerivedMesh *) dm;
1802
1803 #ifdef WITH_OPENSUBDIV
1804         if (ccgdm->useGpuBackend) {
1805                 /* TODO(sergey): We currently only support all edges drawing. */
1806                 if (ccgSubSurf_prepareGLMesh(ccgdm->ss, true, -1)) {
1807                         ccgSubSurf_drawGLMesh(ccgdm->ss, false, -1, -1);
1808                 }
1809                 return;
1810         }
1811 #endif
1812
1813         ccgdm_pbvh_update(ccgdm);
1814
1815 /* old debug feature for edges, unsupported for now */
1816 #if 0
1817         int useAging = 0;
1818
1819         if (!(G.f & G_BACKBUFSEL)) {
1820                 CCGSubSurf *ss = ccgdm->ss;
1821                 ccgSubSurf_getUseAgeCounts(ss, &useAging, NULL, NULL, NULL);
1822
1823                 /* it needs some way to upload this to VBO now */
1824                 if (useAging) {
1825                         int ageCol = 255 - ccgSubSurf_getEdgeAge(ss, e) * 4;
1826                         glColor3ub(0, ageCol > 0 ? ageCol : 0, 0);
1827                 }
1828         }
1829 #endif
1830
1831         GPU_edge_setup(dm);
1832         gdo = dm->drawObject;
1833         if (gdo->edges && gdo->points) {
1834                 if (drawAllEdges && drawLooseEdges) {
1835                         GPU_buffer_draw_elements(gdo->edges, GL_LINES, 0, (gdo->totedge - gdo->totinterior) * 2);
1836                 }
1837                 else if (drawAllEdges) {
1838                         GPU_buffer_draw_elements(gdo->edges, GL_LINES, 0, gdo->loose_edge_offset * 2);
1839                 }
1840                 else {
1841                         GPU_buffer_draw_elements(gdo->edges, GL_LINES, 0, gdo->tot_edge_drawn * 2);
1842                         GPU_buffer_draw_elements(gdo->edges, GL_LINES, gdo->loose_edge_offset * 2, gdo->tot_loose_edge_drawn * 2);
1843                 }
1844         }
1845
1846         if (gdo->edges && ccgdm->drawInteriorEdges) {
1847                 GPU_buffer_draw_elements(gdo->edges, GL_LINES, gdo->interior_offset * 2, gdo->totinterior * 2);
1848         }
1849         GPU_buffers_unbind();
1850 }
1851
1852 static void ccgDM_drawLooseEdges(DerivedMesh *dm)
1853 {
1854         int start;
1855         int count;
1856
1857 #ifdef WITH_OPENSUBDIV
1858         CCGDerivedMesh *ccgdm = (CCGDerivedMesh *) dm;
1859         if (ccgdm->useGpuBackend) {
1860                 /* TODO(sergey): Needs implementation. */
1861                 return;
1862         }
1863 #endif
1864
1865         GPU_edge_setup(dm);
1866
1867         start = (dm->drawObject->loose_edge_offset * 2);
1868         count = (dm->drawObject->interior_offset - dm->drawObject->loose_edge_offset) * 2;
1869
1870         if (count) {
1871                 GPU_buffer_draw_elements(dm->drawObject->edges, GL_LINES, start, count);
1872         }
1873
1874         GPU_buffers_unbind();
1875 }
1876
1877 static void ccgDM_NormalFast(float *a, float *b, float *c, float *d, float no[3])
1878 {
1879         float a_cX = c[0] - a[0], a_cY = c[1] - a[1], a_cZ = c[2] - a[2];
1880         float b_dX = d[0] - b[0], b_dY = d[1] - b[1], b_dZ = d[2] - b[2];
1881
1882         no[0] = b_dY * a_cZ - b_dZ * a_cY;
1883         no[1] = b_dZ * a_cX - b_dX * a_cZ;
1884         no[2] = b_dX * a_cY - b_dY * a_cX;
1885         
1886         normalize_v3(no);
1887 }
1888
1889
1890 static void ccgDM_glNormalFast(float *a, float *b, float *c, float *d)
1891 {
1892         float a_cX = c[0] - a[0], a_cY = c[1] - a[1], a_cZ = c[2] - a[2];
1893         float b_dX = d[0] - b[0], b_dY = d[1] - b[1], b_dZ = d[2] - b[2];
1894         float no[3];
1895         
1896         no[0] = b_dY * a_cZ - b_dZ * a_cY;
1897         no[1] = b_dZ * a_cX - b_dX * a_cZ;
1898         no[2] = b_dX * a_cY - b_dY * a_cX;
1899
1900         /* don't normalize, GL_NORMALIZE is enabled */
1901         glNormal3fv(no);
1902 }
1903
1904 /* Only used by non-editmesh types */
1905 static void ccgDM_buffer_copy_normal(
1906         DerivedMesh *dm, short *varray)
1907 {
1908         CCGDerivedMesh *ccgdm = (CCGDerivedMesh *) dm;
1909         CCGSubSurf *ss = ccgdm->ss;
1910         CCGKey key;
1911         const float (*lnors)[3] = dm->getLoopDataArray(dm, CD_NORMAL);
1912         int gridSize = ccgSubSurf_getGridSize(ss);
1913         int gridFaces = gridSize - 1;
1914         DMFlagMat *faceFlags = ccgdm->faceFlags;
1915         int i, totface = ccgSubSurf_getNumFaces(ss);
1916         int shademodel;
1917         int start = 0;
1918
1919         /* we are in sculpt mode, disable loop normals (since they won't get updated) */
1920         if (ccgdm->pbvh)
1921                 lnors = NULL;
1922
1923         CCG_key_top_level(&key, ss);
1924
1925         for (i = 0; i < totface; i++) {
1926                 CCGFace *f = ccgdm->faceMap[i].face;
1927                 int S, x, y, numVerts = ccgSubSurf_getFaceNumVerts(f);
1928                 int index = GET_INT_FROM_POINTER(ccgSubSurf_getFaceFaceHandle(f));
1929                 const float (*ln)[3] = NULL;
1930
1931                 if (faceFlags) {
1932                         shademodel = (lnors || (faceFlags[index].flag & ME_SMOOTH)) ? GL_SMOOTH : GL_FLAT;
1933                 }
1934                 else {
1935                         shademodel = GL_SMOOTH;
1936                 }
1937
1938                 if (lnors) {
1939                         ln = lnors;
1940                         lnors += gridFaces * gridFaces * numVerts * 4;
1941                 }
1942
1943                 for (S = 0; S < numVerts; S++) {
1944                         CCGElem *faceGridData = ccgSubSurf_getFaceGridDataArray(ss, f, S);
1945
1946                         if (ln) {
1947                                 /* Can't use quad strips here... */
1948                                 for (y = 0; y < gridFaces; y ++) {
1949                                         for (x = 0; x < gridFaces; x ++) {
1950                                                 normal_float_to_short_v3(&varray[start + 0],  ln[0]);
1951                                                 normal_float_to_short_v3(&varray[start + 4],  ln[3]);
1952                                                 normal_float_to_short_v3(&varray[start + 8],  ln[2]);
1953                                                 normal_float_to_short_v3(&varray[start + 12], ln[1]);
1954
1955                                                 start += 16;
1956                                                 ln += 4;
1957                                         }
1958                                 }
1959                         }
1960                         else if (shademodel == GL_SMOOTH) {
1961                                 for (y = 0; y < gridFaces; y ++) {
1962                                         for (x = 0; x < gridFaces; x ++) {
1963                                                 float *a = CCG_grid_elem_no(&key, faceGridData, x, y );
1964                                                 float *b = CCG_grid_elem_no(&key, faceGridData, x + 1, y);
1965                                                 float *c = CCG_grid_elem_no(&key, faceGridData, x + 1, y + 1);
1966                                                 float *d = CCG_grid_elem_no(&key, faceGridData, x, y + 1);
1967
1968                                                 normal_float_to_short_v3(&varray[start], a);
1969                                                 normal_float_to_short_v3(&varray[start + 4], b);
1970                                                 normal_float_to_short_v3(&varray[start + 8], c);
1971                                                 normal_float_to_short_v3(&varray[start + 12], d);
1972
1973                                                 start += 16;
1974                                         }
1975                                 }
1976                         }
1977                         else {
1978                                 for (y = 0; y < gridFaces; y ++) {
1979                                         for (x = 0; x < gridFaces; x ++) {
1980                                                 float f_no[3];
1981                                                 short f_no_s[3];
1982
1983                                                 float *a = CCG_grid_elem_co(&key, faceGridData, x, y );
1984                                                 float *b = CCG_grid_elem_co(&key, faceGridData, x + 1, y );
1985                                                 float *c = CCG_grid_elem_co(&key, faceGridData, x + 1, y + 1);
1986                                                 float *d = CCG_grid_elem_co(&key, faceGridData, x, y + 1);
1987
1988                                                 ccgDM_NormalFast(a, b, c, d, f_no);
1989                                                 normal_float_to_short_v3(f_no_s, f_no);
1990         
1991                                                 copy_v3_v3_short(&varray[start], f_no_s);
1992                                                 copy_v3_v3_short(&varray[start + 4], f_no_s);
1993                                                 copy_v3_v3_short(&varray[start + 8], f_no_s);
1994                                                 copy_v3_v3_short(&varray[start + 12], f_no_s);
1995
1996                                                 start += 16;
1997                                         }
1998                                 }
1999                         }
2000                 }
2001         }
2002 }
2003
2004 typedef struct FaceCount {
2005         unsigned int i_visible;
2006         unsigned int i_hidden;
2007         unsigned int i_tri_visible;
2008         unsigned int i_tri_hidden;
2009 } FaceCount;
2010
2011
2012 /* Only used by non-editmesh types */
2013 static void ccgDM_buffer_copy_triangles(
2014         DerivedMesh *dm, unsigned int *varray,
2015         const int *mat_orig_to_new)
2016 {
2017         GPUBufferMaterial *gpumat, *gpumaterials = dm->drawObject->materials;
2018         const int gpu_totmat = dm->drawObject->totmaterial;
2019         const short dm_totmat = dm->totmat;
2020         CCGDerivedMesh *ccgdm = (CCGDerivedMesh *) dm;
2021         CCGSubSurf *ss = ccgdm->ss;
2022         CCGKey key;
2023         int gridSize = ccgSubSurf_getGridSize(ss);
2024         int gridFaces = gridSize - 1;
2025         DMFlagMat *faceFlags = ccgdm->faceFlags;
2026         int i, totface = ccgSubSurf_getNumFaces(ss);
2027         short mat_nr = -1;
2028         int start;
2029         int totloops = 0;
2030         FaceCount *fc = MEM_mallocN(sizeof(*fc) * gpu_totmat, "gpumaterial.facecount");
2031
2032         CCG_key_top_level(&key, ss);
2033
2034         for (i = 0; i < gpu_totmat; i++) {
2035                 fc[i].i_visible = 0;
2036                 fc[i].i_tri_visible = 0;
2037                 fc[i].i_hidden = gpumaterials[i].totpolys - 1;
2038                 fc[i].i_tri_hidden = gpumaterials[i].totelements - 1;
2039         }
2040
2041         for (i = 0; i < totface; i++) {
2042                 CCGFace *f = ccgdm->faceMap[i].face;
2043                 int S, x, y, numVerts = ccgSubSurf_getFaceNumVerts(f);
2044                 int index = GET_INT_FROM_POINTER(ccgSubSurf_getFaceFaceHandle(f));
2045                 bool is_hidden;
2046                 int mati;
2047
2048                 if (faceFlags) {
2049                         mat_nr = ME_MAT_NR_TEST(faceFlags[index].mat_nr, dm_totmat);
2050                         is_hidden = (faceFlags[index].flag & ME_HIDE) != 0;
2051                 }
2052                 else {
2053                         mat_nr = 0;
2054                         is_hidden = false;
2055                 }
2056                 mati = mat_orig_to_new[mat_nr];
2057                 gpumat = dm->drawObject->materials + mati;
2058
2059                 if (is_hidden) {
2060                         for (S = 0; S < numVerts; S++) {
2061                                 for (y = 0; y < gridFaces; y++) {
2062                                         for (x = 0; x < gridFaces; x++) {
2063                                                 start = gpumat->start + fc[mati].i_tri_hidden;
2064
2065                                                 varray[start--] = totloops;
2066                                                 varray[start--] = totloops + 2;
2067                                                 varray[start--] = totloops + 3;
2068
2069                                                 varray[start--] = totloops;
2070                                                 varray[start--] = totloops + 1;
2071                                                 varray[start--] = totloops + 2;
2072
2073                                                 fc[mati].i_tri_hidden -= 6;
2074
2075                                                 totloops += 4;
2076                                         }
2077                                 }
2078                         }
2079                         gpumat->polys[fc[mati].i_hidden--] = i;
2080                 }
2081                 else {
2082                         for (S = 0; S < numVerts; S++) {
2083                                 for (y = 0; y < gridFaces; y++) {
2084                                         for (x = 0; x < gridFaces; x++) {
2085                                                 start = gpumat->start + fc[mati].i_tri_visible;
2086
2087                                                 varray[start++] = totloops + 3;
2088                                                 varray[start++] = totloops + 2;
2089                                                 varray[start++] = totloops;
2090
2091                                                 varray[start++] = totloops + 2;
2092                                                 varray[start++] = totloops + 1;
2093                                                 varray[start++] = totloops;
2094
2095                                                 fc[mati].i_tri_visible += 6;
2096
2097                                                 totloops += 4;
2098                                         }
2099                                 }
2100                         }
2101                         gpumat->polys[fc[mati].i_visible++] = i;
2102                 }
2103         }
2104
2105         /* set the visible polygons */
2106         for (i = 0; i < gpu_totmat; i++) {
2107                 gpumaterials[i].totvisiblepolys = fc[i].i_visible;
2108         }
2109
2110         MEM_freeN(fc);
2111 }
2112
2113
2114 /* Only used by non-editmesh types */
2115 static void ccgDM_buffer_copy_vertex(
2116         DerivedMesh *dm, void *varray_p)
2117 {
2118         float *varray = varray_p;
2119         CCGDerivedMesh *ccgdm = (CCGDerivedMesh *) dm;
2120         CCGSubSurf *ss = ccgdm->ss;
2121         CCGKey key;
2122         int gridSize = ccgSubSurf_getGridSize(ss);
2123         int gridFaces = gridSize - 1;
2124         int i, totface = ccgSubSurf_getNumFaces(ss);
2125         int totedge = ccgSubSurf_getNumEdges(ss);
2126         int start = 0;
2127         int edgeSize = ccgSubSurf_getEdgeSize(ss);
2128
2129         CCG_key_top_level(&key, ss);
2130
2131         for (i = 0; i < totface; i++) {
2132                 CCGFace *f = ccgdm->faceMap[i].face;
2133                 int S, x, y, numVerts = ccgSubSurf_getFaceNumVerts(f);
2134                 
2135                 for (S = 0; S < numVerts; S++) {
2136                         CCGElem *faceGridData = ccgSubSurf_getFaceGridDataArray(ss, f, S);
2137                         for (y = 0; y < gridFaces; y++) {
2138                                 for (x = 0; x < gridFaces; x++) {
2139                                         float *a = CCG_grid_elem_co(&key, faceGridData, x, y);
2140                                         float *b = CCG_grid_elem_co(&key, faceGridData, x + 1, y);
2141                                         float *c = CCG_grid_elem_co(&key, faceGridData, x + 1, y + 1);
2142                                         float *d = CCG_grid_elem_co(&key, faceGridData, x, y + 1);
2143
2144                                         copy_v3_v3(&varray[start], a);
2145                                         copy_v3_v3(&varray[start + 3], b);
2146                                         copy_v3_v3(&varray[start + 6], c);
2147                                         copy_v3_v3(&varray[start + 9], d);
2148
2149                                         start += 12;
2150                                 }
2151                         }
2152                 }
2153         }
2154
2155         /* upload loose points */
2156         for (i = 0; i < totedge; i++) {
2157                 CCGEdge *e = ccgdm->edgeMap[i].edge;
2158                 CCGElem *edgeData = ccgSubSurf_getEdgeDataArray(ss, e);
2159
2160                 if (!ccgSubSurf_getEdgeNumFaces(e)) {
2161                         int j = 0;
2162                         for (j = 0; j < edgeSize; j++) {
2163                                 copy_v3_v3(&varray[start], CCG_elem_offset_co(&key, edgeData, j));
2164                                 start += 3;
2165                         }
2166                 }
2167         }
2168 }
2169
2170 /* Only used by non-editmesh types */
2171 static void ccgDM_buffer_copy_color(
2172         DerivedMesh *dm, unsigned char *varray,
2173         const void *user_data)
2174 {
2175         CCGDerivedMesh *ccgdm = (CCGDerivedMesh *) dm;
2176         CCGSubSurf *ss = ccgdm->ss;
2177         CCGKey key;
2178         const unsigned char *mloopcol = user_data;
2179         int gridSize = ccgSubSurf_getGridSize(ss);
2180         int gridFaces = gridSize - 1;
2181         int i, totface = ccgSubSurf_getNumFaces(ss);
2182         int start = 0;
2183         int iface = 0;
2184
2185         CCG_key_top_level(&key, ss);
2186
2187
2188         for (i = 0; i < totface; i++) {
2189                 CCGFace *f = ccgdm->faceMap[i].face;
2190                 int S, x, y, numVerts = ccgSubSurf_getFaceNumVerts(f);
2191
2192                 for (S = 0; S < numVerts; S++) {
2193                         for (y = 0; y < gridFaces; y++) {
2194                                 for (x = 0; x < gridFaces; x++) {
2195                                         copy_v3_v3_uchar(&varray[start + 0], &mloopcol[iface * 16 + 0]);
2196                                         copy_v3_v3_uchar(&varray[start + 3], &mloopcol[iface * 16 + 12]);
2197                                         copy_v3_v3_uchar(&varray[start + 6], &mloopcol[iface * 16 + 8]);
2198                                         copy_v3_v3_uchar(&varray[start + 9], &mloopcol[iface * 16 + 4]);
2199
2200                                         start += 12;
2201                                         iface++;
2202                                 }
2203                         }
2204                 }
2205         }
2206 }
2207
2208 static void ccgDM_buffer_copy_uv(
2209         DerivedMesh *dm, void *varray_p)
2210 {
2211         float *varray = varray_p;
2212         CCGDerivedMesh *ccgdm = (CCGDerivedMesh *) dm;
2213         CCGSubSurf *ss = ccgdm->ss;
2214         CCGKey key;
2215         MLoopUV *mloopuv = DM_get_loop_data_layer(dm, CD_MLOOPUV);
2216         int gridSize = ccgSubSurf_getGridSize(ss);
2217         int gridFaces = gridSize - 1;
2218         int i, totface = ccgSubSurf_getNumFaces(ss);
2219         int start = 0;
2220
2221         CCG_key_top_level(&key, ss);
2222
2223         for (i = 0; i < totface; i++) {
2224                 CCGFace *f = ccgdm->faceMap[i].face;
2225                 int S, x, y, numVerts = ccgSubSurf_getFaceNumVerts(f);
2226
2227                 for (S = 0; S < numVerts; S++) {
2228                         for (y = 0; y < gridFaces; y++) {
2229                                 for (x = 0; x < gridFaces; x++) {
2230                                         copy_v2_v2(&varray[start + 0], mloopuv[0].uv);
2231                                         copy_v2_v2(&varray[start + 2], mloopuv[3].uv);
2232                                         copy_v2_v2(&varray[start + 4], mloopuv[2].uv);
2233                                         copy_v2_v2(&varray[start + 6], mloopuv[1].uv);
2234
2235                                         mloopuv += 4;
2236                                         start += 8;
2237                                 }
2238                         }
2239                 }
2240         }
2241 }
2242
2243 static void ccgDM_buffer_copy_uv_texpaint(
2244         DerivedMesh *dm, float *varray)
2245 {
2246         CCGDerivedMesh *ccgdm = (CCGDerivedMesh *) dm;
2247         CCGSubSurf *ss = ccgdm->ss;
2248         CCGKey key;
2249         int gridSize = ccgSubSurf_getGridSize(ss);
2250         int gridFaces = gridSize - 1;
2251         int i, totface = ccgSubSurf_getNumFaces(ss);
2252         int start = 0;
2253         DMFlagMat *faceFlags = ccgdm->faceFlags;
2254         int dm_totmat = dm->totmat;
2255         MLoopUV **mloopuv_base;
2256         MLoopUV  *stencil_base;
2257         int stencil;
2258
2259         CCG_key_top_level(&key, ss);
2260
2261         /* should have been checked for before, reassert */
2262         BLI_assert(DM_get_loop_data_layer(dm, CD_MLOOPUV));
2263         mloopuv_base = MEM_mallocN(dm_totmat * sizeof(*mloopuv_base), "texslots");
2264
2265         for (i = 0; i < dm_totmat; i++) {
2266                 mloopuv_base[i] = DM_paint_uvlayer_active_get(dm, i);
2267         }
2268
2269         stencil = CustomData_get_stencil_layer(&dm->loopData, CD_MLOOPUV);
2270         stencil_base = CustomData_get_layer_n(&dm->loopData, CD_MLOOPUV, stencil);
2271
2272         start = 0;
2273
2274         for (i = 0; i < totface; i++) {
2275                 CCGFace *f = ccgdm->faceMap[i].face;
2276                 int S, x, y, numVerts = ccgSubSurf_getFaceNumVerts(f);
2277                 int index = GET_INT_FROM_POINTER(ccgSubSurf_getFaceFaceHandle(f));
2278                 int matnr;
2279
2280                 if (faceFlags) {
2281                         matnr = faceFlags[index].mat_nr;
2282                 }
2283                 else {
2284                         matnr = 0;
2285                 }
2286
2287                 for (S = 0; S < numVerts; S++) {
2288                         for (y = 0; y < gridFaces; y++) {
2289                                 for (x = 0; x < gridFaces; x++) {
2290                                         /* divide by 4, gives us current loop-index */
2291                                         unsigned int i_ml = start / 4;
2292                                         copy_v2_v2(&varray[start + 0],  mloopuv_base[matnr][i_ml + 0].uv);
2293                                         copy_v2_v2(&varray[start + 2],         stencil_base[i_ml + 0].uv);
2294                                         copy_v2_v2(&varray[start + 4],  mloopuv_base[matnr][i_ml + 3].uv);
2295                                         copy_v2_v2(&varray[start + 6],         stencil_base[i_ml + 3].uv);
2296                                         copy_v2_v2(&varray[start + 8],  mloopuv_base[matnr][i_ml + 2].uv);
2297                                         copy_v2_v2(&varray[start + 10],        stencil_base[i_ml + 2].uv);
2298                                         copy_v2_v2(&varray[start + 12], mloopuv_base[matnr][i_ml + 1].uv);
2299                                         copy_v2_v2(&varray[start + 14],        stencil_base[i_ml + 1].uv);
2300                                         start += 16;
2301                                 }
2302                         }
2303                 }
2304         }
2305
2306         MEM_freeN(mloopuv_base);
2307 }
2308
2309 static void ccgDM_buffer_copy_uvedge(
2310         DerivedMesh *dm, float *varray)
2311 {
2312         int i, totpoly;
2313         int start;
2314         const MLoopUV *mloopuv;
2315 #ifndef USE_LOOP_LAYOUT_FAST
2316         const MPoly *mpoly = dm->getPolyArray(dm);
2317 #endif
2318
2319         if ((mloopuv = DM_get_loop_data_layer(dm, CD_MLOOPUV)) == NULL) {
2320                 return;
2321         }
2322
2323         totpoly = dm->getNumPolys(dm);
2324         start = 0;
2325
2326 #ifndef USE_LOOP_LAYOUT_FAST
2327         for (i = 0; i < totpoly; i++, mpoly++) {
2328                 for (j = 0; j < mpoly->totloop; j++) {
2329                         copy_v2_v2(&varray[start], mloopuv[mpoly->loopstart + j].uv);
2330                         copy_v2_v2(&varray[start + 2], mloopuv[mpoly->loopstart + (j + 1) % mpoly->totloop].uv);
2331                         start += 4;
2332                 }
2333         }
2334 #else
2335         for (i = 0; i < totpoly; i++) {
2336                 copy_v2_v2(&varray[start +  0], mloopuv[(i * 4) + 0].uv);
2337                 copy_v2_v2(&varray[start +  2], mloopuv[(i * 4) + 1].uv);
2338
2339                 copy_v2_v2(&varray[start +  4], mloopuv[(i * 4) + 1].uv);
2340                 copy_v2_v2(&varray[start +  6], mloopuv[(i * 4) + 2].uv);
2341
2342                 copy_v2_v2(&varray[start +  8], mloopuv[(i * 4) + 2].uv);
2343                 copy_v2_v2(&varray[start + 10], mloopuv[(i * 4) + 3].uv);
2344
2345                 copy_v2_v2(&varray[start + 12], mloopuv[(i * 4) + 3].uv);
2346                 copy_v2_v2(&varray[start + 14], mloopuv[(i * 4) + 0].uv);
2347
2348                 start += 16;
2349         }
2350 #endif
2351 }
2352
2353 static void ccgDM_buffer_copy_edge(
2354         DerivedMesh *dm, unsigned int *varray)
2355 {
2356         CCGDerivedMesh *ccgdm = (CCGDerivedMesh *) dm;
2357         CCGSubSurf *ss = ccgdm->ss;
2358         /* getEdgeSuze returns num of verts, edges is one less */
2359         int i, j, edgeSize = ccgSubSurf_getEdgeSize(ss) - 1;
2360         int totedge = ccgSubSurf_getNumEdges(ss);
2361         int grid_face_side = ccgSubSurf_getGridSize(ss) - 1;
2362         int totface = ccgSubSurf_getNumFaces(ss);
2363         unsigned int index_start;
2364         unsigned int tot_interior = 0;
2365         unsigned int grid_tot_face = grid_face_side * grid_face_side;
2366
2367         unsigned int iloose, inorm, iloosehidden, inormhidden;
2368         unsigned int tot_loose_hidden = 0, tot_loose = 0;
2369         unsigned int tot_hidden = 0, tot = 0;
2370         unsigned int iloosevert;
2371         /* int tot_interior = 0; */
2372
2373         /* first, handle hidden/loose existing edges, then interior edges */
2374         for (j = 0; j < totedge; j++) {
2375                 CCGEdge *e = ccgdm->edgeMap[j].edge;
2376
2377                 if (ccgdm->edgeFlags && !(ccgdm->edgeFlags[j] & ME_EDGEDRAW)) {
2378                         if (!ccgSubSurf_getEdgeNumFaces(e)) tot_loose_hidden++;
2379                         else tot_hidden++;
2380                 }
2381                 else {
2382                         if (!ccgSubSurf_getEdgeNumFaces(e)) tot_loose++;
2383                         else tot++;
2384                 }
2385         }
2386
2387         inorm = 0;
2388         inormhidden = tot * edgeSize;
2389         iloose = (tot + tot_hidden) * edgeSize;
2390         iloosehidden = (tot + tot_hidden + tot_loose) * edgeSize;
2391         iloosevert = dm->drawObject->tot_loop_verts;
2392
2393         /* part one, handle all normal edges */
2394         for (j = 0; j < totedge; j++) {
2395                 CCGFace *f;
2396                 int fhandle = 0;
2397                 int totvert = 0;
2398                 unsigned int S = 0;
2399                 CCGEdge *e = ccgdm->edgeMap[j].edge;
2400                 bool isloose = !ccgSubSurf_getEdgeNumFaces(e);
2401
2402                 if (!isloose) {
2403                         CCGVert *v1, *v2;
2404                         CCGVert *ev1 = ccgSubSurf_getEdgeVert0(e);
2405                         CCGVert *ev2 = ccgSubSurf_getEdgeVert1(e);
2406
2407                         f = ccgSubSurf_getEdgeFace(e, 0);
2408                         fhandle = GET_INT_FROM_POINTER(ccgSubSurf_getFaceFaceHandle(f));
2409                         totvert = ccgSubSurf_getFaceNumVerts(f);
2410
2411                         /* find the index of vertices in the face */
2412                         for (i = 0; i < totvert; i++) {
2413                                 v1 = ccgSubSurf_getFaceVert(f, i);
2414                                 v2 = ccgSubSurf_getFaceVert(f, (i + 1) % totvert);
2415
2416                                 if ((ev1 == v1 && ev2 == v2) || (ev1 == v2 && ev2 == v1)) {
2417                                         S = i;
2418                                         break;
2419                                 }
2420                         }
2421                 }
2422
2423                 if (ccgdm->edgeFlags && !(ccgdm->edgeFlags[j] & ME_EDGEDRAW)) {
2424                         if (isloose) {
2425                                 for (i = 0; i < edgeSize; i++) {
2426                                         varray[iloosehidden * 2] = iloosevert;
2427                                         varray[iloosehidden * 2 + 1] = iloosevert + 1;
2428                                         iloosehidden++;
2429                                         iloosevert++;
2430                                 }
2431                                 /* we are through with this loose edge and moving to the next, so increase by one */
2432                                 iloosevert++;
2433                         }
2434                         else {
2435                                 index_start = ccgdm->faceMap[fhandle].startFace;
2436
2437                                 for (i = 0; i < grid_face_side; i++) {
2438                                         varray[inormhidden * 2] = (index_start + S * grid_tot_face + i * grid_face_side + grid_face_side - 1) * 4 + 1;
2439                                         varray[inormhidden * 2 + 1] = (index_start + S * grid_tot_face + i * grid_face_side + grid_face_side - 1) * 4 + 2;
2440                                         varray[inormhidden * 2 + 2] = (index_start + ((S + 1) % totvert) * grid_tot_face + grid_face_side * (grid_face_side - 1) + i) * 4 + 2;
2441                                         varray[inormhidden * 2 + 3] = (index_start + ((S + 1) % totvert) * grid_tot_face + grid_face_side * (grid_face_side - 1) + i) * 4 + 3;
2442                                         inormhidden += 2;
2443                                 }
2444                         }
2445                 }
2446                 else {
2447                         if (isloose) {
2448                                 for (i = 0; i < edgeSize; i++) {
2449                                         varray[iloose * 2] = iloosevert;
2450                                         varray[iloose * 2 + 1] = iloosevert + 1;
2451                                         iloose++;
2452                                         iloosevert++;
2453                                 }
2454                                 /* we are through with this loose edge and moving to the next, so increase by one */
2455                                 iloosevert++;
2456                         }
2457                         else {
2458                                 index_start = ccgdm->faceMap[fhandle].startFace;
2459
2460                                 for (i = 0; i < grid_face_side; i++) {
2461                                         varray[inorm * 2] = (index_start + S * grid_tot_face + i * grid_face_side + grid_face_side - 1) * 4 + 1;
2462                                         varray[inorm * 2 + 1] = (index_start + S * grid_tot_face + i * grid_face_side + grid_face_side - 1) * 4 + 2;
2463                                         varray[inorm * 2 + 2] = (index_start + ((S + 1) % totvert) * grid_tot_face + grid_face_side * (grid_face_side - 1) + i) * 4 + 2;
2464                                         varray[inorm * 2 + 3] = (index_start + ((S + 1) % totvert) * grid_tot_face + grid_face_side * (grid_face_side - 1) + i) * 4 + 3;
2465                                         inorm += 2;
2466                                 }
2467                         }
2468                 }
2469         }
2470
2471         /* part two, handle interior edges */
2472         inorm = totedge * grid_face_side * 2;
2473
2474         index_start = 0;
2475         for (i = 0; i < totface; i++) {
2476                 CCGFace *f = ccgdm->faceMap[i].face;
2477                 unsigned int S, x, y, numVerts = ccgSubSurf_getFaceNumVerts(f);
2478
2479                 for (S = 0; S < numVerts; S++) {
2480                         for (x = 1; x < grid_face_side; x++) {
2481                                 for (y = 0; y < grid_face_side; y++) {
2482                                         unsigned int tmp = (index_start + x * grid_face_side + y) * 4;
2483                                         varray[inorm * 2] = tmp;
2484                                         varray[inorm * 2 + 1] = tmp + 1;
2485                                         inorm++;
2486                                 }
2487                         }
2488                         for (x = 0; x < grid_face_side; x++) {
2489                                 for (y = 0; y < grid_face_side; y++) {
2490                                         unsigned int tmp = (index_start + x * grid_face_side + y) * 4;
2491                                         varray[inorm * 2] = tmp + 3;
2492                                         varray[inorm * 2 + 1] = tmp;
2493                                         inorm++;
2494                                 }
2495                         }
2496
2497                         tot_interior += grid_face_side * (2 * grid_face_side - 1);
2498                         index_start += grid_tot_face;
2499                 }
2500         }
2501
2502         dm->drawObject->tot_loose_edge_drawn = tot_loose * edgeSize;
2503         dm->drawObject->loose_edge_offset = (tot + tot_hidden) * edgeSize;
2504         dm->drawObject->tot_edge_drawn = tot * edgeSize;
2505
2506         dm->drawObject->interior_offset = totedge * edgeSize;
2507         dm->drawObject->totinterior = tot_interior;
2508 }
2509
2510 static void ccgDM_copy_gpu_data(
2511         DerivedMesh *dm, int type, void *varray_p,
2512         const int *mat_orig_to_new, const void *user_data)
2513 {
2514         /* 'varray_p' cast is redundant but include for self-documentation */
2515         switch (type) {
2516                 case GPU_BUFFER_VERTEX:
2517                         ccgDM_buffer_copy_vertex(dm, (float *)varray_p);
2518                         break;
2519                 case GPU_BUFFER_NORMAL:
2520                         ccgDM_buffer_copy_normal(dm, (short *)varray_p);
2521                         break;
2522                 case GPU_BUFFER_UV:
2523                         ccgDM_buffer_copy_uv(dm, (float *)varray_p);
2524                         break;
2525                 case GPU_BUFFER_UV_TEXPAINT:
2526                         ccgDM_buffer_copy_uv_texpaint(dm, (float *)varray_p);
2527                         break;
2528                 case GPU_BUFFER_COLOR:
2529                         ccgDM_buffer_copy_color(dm, (unsigned char *)varray_p, user_data);
2530                         break;
2531                 case GPU_BUFFER_UVEDGE:
2532                         ccgDM_buffer_copy_uvedge(dm, (float *)varray_p);
2533                         break;
2534                 case GPU_BUFFER_EDGE:
2535                         ccgDM_buffer_copy_edge(dm, (unsigned int *)varray_p);
2536                         break;
2537                 case GPU_BUFFER_TRIANGLES:
2538                         ccgDM_buffer_copy_triangles(dm, (unsigned int *)varray_p, mat_orig_to_new);
2539                         break;
2540                 default:
2541                         break;
2542         }
2543 }
2544
2545 static GPUDrawObject *ccgDM_GPUObjectNew(DerivedMesh *dm)
2546 {
2547         CCGDerivedMesh *ccgdm = (CCGDerivedMesh *) dm;
2548         CCGSubSurf *ss = ccgdm->ss;
2549         GPUDrawObject *gdo;
2550         DMFlagMat *faceFlags = ccgdm->faceFlags;
2551         int gridFaces = ccgSubSurf_getGridSize(ss) - 1;
2552         const short dm_totmat = (faceFlags) ? dm->totmat : 1;
2553         GPUBufferMaterial *matinfo;
2554         int i;
2555         unsigned int tot_internal_edges = 0;
2556         int edgeVerts = ccgSubSurf_getEdgeSize(ss);
2557         int edgeSize = edgeVerts - 1;
2558
2559         int totedge = ccgSubSurf_getNumEdges(ss);
2560         int totface = ccgSubSurf_getNumFaces(ss);
2561
2562         /* object contains at least one material (default included) so zero means uninitialized dm */
2563         BLI_assert(dm_totmat != 0);
2564
2565         matinfo = MEM_callocN(sizeof(*matinfo) * dm_totmat, "GPU_drawobject_new.mat_orig_to_new");
2566         
2567         if (faceFlags) {
2568                 for (i = 0; i < totface; i++) {
2569                         CCGFace *f = ccgdm->faceMap[i].face;
2570                         int numVerts = ccgSubSurf_getFaceNumVerts(f);
2571                         int index = GET_INT_FROM_POINTER(ccgSubSurf_getFaceFaceHandle(f));
2572                         const short new_matnr = ME_MAT_NR_TEST(faceFlags[index].mat_nr, dm_totmat);
2573                         matinfo[new_matnr].totelements += numVerts * gridFaces * gridFaces * 6;
2574                         matinfo[new_matnr].totloops += numVerts * gridFaces * gridFaces * 4;
2575                         matinfo[new_matnr].totpolys++;
2576                         tot_internal_edges += numVerts * gridFaces * (2 * gridFaces - 1);
2577                 }
2578         }
2579         else {
2580                 for (i = 0; i < totface; i++) {
2581                         CCGFace *f = ccgdm->faceMap[i].face;
2582                         int numVerts = ccgSubSurf_getFaceNumVerts(f);
2583                         matinfo[0].totelements += numVerts * gridFaces * gridFaces * 6;
2584                         matinfo[0].totloops += numVerts * gridFaces * gridFaces * 4;
2585                         matinfo[0].totpolys++;
2586                         tot_internal_edges += numVerts * gridFaces * (2 * gridFaces - 1);
2587                 }
2588         }
2589         
2590         /* create the GPUDrawObject */
2591         gdo = MEM_callocN(sizeof(GPUDrawObject), "GPUDrawObject");
2592         gdo->totvert = 0; /* used to count indices, doesn't really matter for ccgsubsurf */
2593         gdo->totedge = (totedge * edgeSize + tot_internal_edges);
2594
2595         GPU_buffer_material_finalize(gdo, matinfo, dm_totmat);
2596
2597         /* store total number of points used for triangles */
2598         gdo->tot_triangle_point = ccgSubSurf_getNumFinalFaces(ss) * 6;
2599         gdo->tot_loop_verts = ccgSubSurf_getNumFinalFaces(ss) * 4;
2600
2601         /* finally, count loose points */
2602         for (i = 0; i < totedge; i++) {
2603                 CCGEdge *e = ccgdm->edgeMap[i].edge;
2604
2605                 if (!ccgSubSurf_getEdgeNumFaces(e))
2606                         gdo->tot_loose_point += edgeVerts;
2607         }
2608
2609         return gdo;
2610 }
2611
2612 /* Only used by non-editmesh types */
2613 static void ccgDM_drawFacesSolid(DerivedMesh *dm, float (*partial_redraw_planes)[4], bool fast, DMSetMaterial setMaterial)
2614 {
2615         int a;
2616         CCGDerivedMesh *ccgdm = (CCGDerivedMesh *) dm;
2617
2618         ccgdm_pbvh_update(ccgdm);
2619
2620         if (ccgdm->pbvh && ccgdm->multires.mmd) {
2621                 if (BKE_pbvh_has_faces(ccgdm->pbvh)) {
2622                         BKE_pbvh_draw(ccgdm->pbvh, partial_redraw_planes, NULL,
2623                                       setMaterial, false, fast);
2624                 }
2625
2626                 return;
2627         }
2628
2629 #ifdef WITH_OPENSUBDIV
2630         if (ccgdm->useGpuBackend) {
2631                 CCGSubSurf *ss = ccgdm->ss;
2632                 const DMFlagMat *faceFlags = ccgdm->faceFlags;
2633                 const int level = ccgSubSurf_getSubdivisionLevels(ss);
2634                 const int face_side = 1 << level;
2635                 const int grid_side = 1 << (level - 1);
2636                 const int face_patches = face_side * face_side;
2637                 const int grid_patches = grid_side * grid_side;
2638                 const int num_base_faces = ccgSubSurf_getNumGLMeshBaseFaces(ss);
2639                 int i, current_patch = 0;
2640                 int mat_nr = -1;
2641                 bool draw_smooth = false;
2642                 int start_draw_patch = -1, num_draw_patches = 0;
2643                 if (UNLIKELY(ccgSubSurf_prepareGLMesh(ss, setMaterial != NULL, -1) == false)) {
2644                         return;
2645                 }
2646                 if (setMaterial == NULL) {
2647                         ccgSubSurf_drawGLMesh(ss,
2648                                               true,
2649                                               -1,
2650                                               -1);
2651                         return;
2652                 }
2653                 for (i = 0; i < num_base_faces; ++i) {
2654                         const int num_face_verts = ccgSubSurf_getNumGLMeshBaseFaceVerts(ss, i);
2655                         const int num_patches = (num_face_verts == 4) ? face_patches
2656                                                                       : num_face_verts * grid_patches;
2657                         int new_matnr;
2658                         bool new_draw_smooth;
2659                         if (faceFlags) {
2660                                 new_draw_smooth = (faceFlags[i].flag & ME_SMOOTH);
2661                                 new_matnr = (faceFlags[i].mat_nr + 1);
2662                         }
2663                         else {
2664                                 new_draw_smooth = true;
2665                                 new_matnr = 1;
2666                         }
2667                         if (new_draw_smooth != draw_smooth || new_matnr != mat_nr) {
2668                                 if (num_draw_patches != 0) {
2669                                         bool do_draw = setMaterial(mat_nr, NULL);
2670                                         if (do_draw) {
2671                                                 glShadeModel(draw_smooth ? GL_SMOOTH : GL_FLAT);
2672                                                 ccgSubSurf_drawGLMesh(ss,
2673                                                                       true,
2674                                                                       start_draw_patch,
2675                                                                       num_draw_patches);
2676                                         }
2677                                 }
2678                                 start_draw_patch = current_patch;
2679                                 num_draw_patches = num_patches;
2680                                 mat_nr = new_matnr;
2681                                 draw_smooth = new_draw_smooth;
2682                         }
2683                         else {
2684                                 num_draw_patches += num_patches;
2685                         }
2686                         current_patch += num_patches;
2687                 }
2688                 if (num_draw_patches != 0) {
2689                         bool do_draw = setMaterial(mat_nr, NULL);
2690                         if (do_draw) {
2691                                 glShadeModel(draw_smooth ? GL_SMOOTH : GL_FLAT);
2692                                 ccgSubSurf_drawGLMesh(ss,
2693                                                       true,
2694                                                       start_draw_patch,
2695                                                       num_draw_patches);
2696                         }
2697                 }
2698                 return;
2699         }
2700 #endif
2701
2702         GPU_vertex_setup(dm);
2703         GPU_normal_setup(dm);
2704         GPU_triangle_setup(dm);
2705         glShadeModel(GL_SMOOTH);
2706         for (a = 0; a < dm->drawObject->totmaterial; a++) {
2707                 if (!setMaterial || setMaterial(dm->drawObject->materials[a].mat_nr + 1, NULL)) {
2708                         GPU_buffer_draw_elements(dm->drawObject->triangles, GL_TRIANGLES, dm->drawObject->materials[a].start,
2709                                                  dm->drawObject->materials[a].totelements);
2710                 }
2711         }
2712         GPU_buffers_unbind();
2713 }
2714
2715 typedef struct {
2716         DMVertexAttribs attribs;
2717         int numdata;
2718
2719         GPUAttrib datatypes[GPU_MAX_ATTRIB]; /* TODO, messing up when switching materials many times - [#21056]*/
2720 } GPUMaterialConv;
2721
2722 /* Only used by non-editmesh types */
2723 static void ccgDM_drawMappedFacesGLSL(DerivedMesh *dm,
2724                                       DMSetMaterial setMaterial,
2725                                       DMSetDrawOptions setDrawOptions,
2726                                       void *userData)
2727 {
2728         CCGDerivedMesh *ccgdm = (CCGDerivedMesh *) dm;
2729         CCGSubSurf *ss = ccgdm->ss;
2730         CCGKey key;
2731         GPUVertexAttribs gattribs;
2732         int a, b;
2733         const DMFlagMat *faceFlags = ccgdm->faceFlags;
2734         unsigned char *varray;
2735         size_t max_element_size = 0;
2736         int tot_loops = 0;
2737         int totpoly = ccgSubSurf_getNumFaces(ss);
2738         int gridSize = ccgSubSurf_getGridSize(ss);
2739         int gridFaces = gridSize - 1;
2740         int edgeSize = ccgSubSurf_getEdgeSize(ss);
2741
2742 #ifdef WITH_OPENSUBDIV
2743         if (ccgdm->useGpuBackend) {
2744                 const int level = ccgSubSurf_getSubdivisionLevels(ss);
2745                 const int face_side = 1 << level;
2746                 const int grid_side = 1 << (level - 1);
2747                 const int face_patches = face_side * face_side;
2748                 const int grid_patches = grid_side * grid_side;
2749                 const int num_base_faces = ccgSubSurf_getNumGLMeshBaseFaces(ss);
2750                 int i, current_patch = 0;
2751                 int mat_nr = -1;
2752                 bool draw_smooth = false;
2753                 int start_draw_patch = -1, num_draw_patches = 0;
2754                 GPU_draw_update_fvar_offset(dm);
2755                 if (UNLIKELY(ccgSubSurf_prepareGLMesh(ss, false, -1) == false)) {
2756                         return;
2757                 }
2758                 for (i = 0; i < num_base_faces; ++i) {
2759                         const int num_face_verts = ccgSubSurf_getNumGLMeshBaseFaceVerts(ss, i);
2760                         const int num_patches = (num_face_verts == 4) ? face_patches
2761                                                                       : num_face_verts * grid_patches;
2762                         int new_matnr;
2763                         bool new_draw_smooth;
2764
2765                         if (faceFlags) {
2766                                 new_draw_smooth = (faceFlags[i].flag & ME_SMOOTH);
2767                                 new_matnr = (faceFlags[i].mat_nr + 1);
2768                         }
2769                         else {
2770                                 new_draw_smooth = true;
2771                                 new_matnr = 1;
2772                         }
2773                         if (new_draw_smooth != draw_smooth || new_matnr != mat_nr) {
2774                                 if (num_draw_patches != 0) {
2775                                         bool do_draw = setMaterial(mat_nr, &gattribs);
2776                                         if (do_draw) {
2777                                                 glShadeModel(draw_smooth ? GL_SMOOTH : GL_FLAT);
2778                                                 ccgSubSurf_drawGLMesh(ss,
2779                                                                       true,
2780                                                                       start_draw_patch,
2781                                                                       num_draw_patches);
2782                                         }
2783                                 }
2784                                 start_draw_patch = current_patch;
2785                                 num_draw_patches = num_patches;
2786                                 mat_nr = new_matnr;
2787                                 draw_smooth = new_draw_smooth;
2788                         }
2789                         else {
2790                                 num_draw_patches += num_patches;
2791                         }
2792                         current_patch += num_patches;
2793                 }
2794                 if (num_draw_patches != 0) {
2795                         bool do_draw = setMaterial(mat_nr, &gattribs);
2796                         if (do_draw) {
2797                                 glShadeModel(draw_smooth ? GL_SMOOTH : GL_FLAT);
2798                                 ccgSubSurf_drawGLMesh(ss,
2799                                                       true,
2800                                                       start_draw_patch,
2801                                                       num_draw_patches);
2802                         }
2803                 }
2804                 return;
2805         }
2806 #endif
2807
2808         glShadeModel(GL_SMOOTH);
2809
2810         CCG_key_top_level(&key, ss);
2811         ccgdm_pbvh_update(ccgdm);
2812
2813         if (setDrawOptions != NULL) {
2814                 const float (*lnors)[3] = dm->getLoopDataArray(dm, CD_NORMAL);
2815                 DMVertexAttribs attribs = {{{NULL}}};
2816                 int i;
2817                 int matnr = -1;
2818                 int do_draw = 0;
2819
2820 #define PASSATTRIB(dx, dy, vert) {                                            \
2821         if (attribs.totorco)                                                      \
2822                 index = getFaceIndex(ss, f, S, x + dx, y + dy, edgeSize, gridSize);   \
2823         else                                                                      \
2824                 index = 0;                                                            \
2825         DM_draw_attrib_vertex(&attribs, a, index, vert, ((a) * 4) + vert);        \
2826 } (void)0
2827
2828                 totpoly = ccgSubSurf_getNumFaces(ss);
2829                 for (a = 0, i = 0; i < totpoly; i++) {
2830                         CCGFace *f = ccgdm->faceMap[i].face;
2831                         const float (*ln)[3] = NULL;
2832                         int S, x, y, drawSmooth;
2833                         int index = GET_INT_FROM_POINTER(ccgSubSurf_getFaceFaceHandle(f));
2834                         int origIndex = ccgDM_getFaceMapIndex(ss, f);
2835
2836                         int numVerts = ccgSubSurf_getFaceNumVerts(f);
2837                         int new_matnr;
2838
2839                         if (faceFlags) {
2840                                 drawSmooth = (lnors || (faceFlags[index].flag & ME_SMOOTH));
2841                                 new_matnr = faceFlags[index].mat_nr + 1;
2842                         }
2843                         else {
2844                                 drawSmooth = 1;
2845                                 new_matnr = 1;
2846                         }
2847
2848                         if (lnors) {
2849                                 ln = lnors;
2850                                 lnors += (gridFaces * gridFaces * numVerts) * 4;
2851                         }
2852
2853                         if (new_matnr != matnr) {
2854                                 do_draw = setMaterial(matnr = new_matnr, &gattribs);
2855                                 if (do_draw)
2856                                         DM_vertex_attributes_from_gpu(dm, &gattribs, &attribs);
2857                         }
2858
2859                         if (!do_draw || (setDrawOptions && (origIndex != ORIGINDEX_NONE) &&
2860                                         (setDrawOptions(userData, origIndex) == DM_DRAW_OPTION_SKIP)))
2861                         {
2862                                 a += gridFaces * gridFaces * numVerts;
2863                                 continue;
2864                         }
2865
2866                         glShadeModel(drawSmooth ? GL_SMOOTH : GL_FLAT);
2867                         for (S = 0; S < numVerts; S++) {
2868                                 CCGElem *faceGridData = ccgSubSurf_getFaceGridDataArray(ss, f, S);
2869                                 CCGElem *vda, *vdb;
2870
2871                                 if (ln) {
2872                                         glBegin(GL_QUADS);
2873                                         for (y = 0; y < gridFaces; y++) {
2874                                                 for (x = 0; x < gridFaces; x++) {
2875                                                         float *aco = CCG_grid_elem_co(&key, faceGridData, x, y);
2876                                                         float *bco = CCG_grid_elem_co(&key, faceGridData, x + 1, y);
2877                                                         float *cco = CCG_grid_elem_co(&key, faceGridData, x + 1, y + 1);
2878                                                         float *dco = CCG_grid_elem_co(&key, faceGridData, x, y + 1);
2879
2880                                                         PASSATTRIB(0, 1, 1);
2881                                                         glNormal3fv(ln[1]);
2882                                                         glVertex3fv(dco);
2883                                                         PASSATTRIB(1, 1, 2);
2884                                                         glNormal3fv(ln[2]);
2885                                                         glVertex3fv(cco);
2886                                                         PASSATTRIB(1, 0, 3);
2887                                                         glNormal3fv(ln[3]);
2888                                                         glVertex3fv(bco);
2889                                                         PASSATTRIB(0, 0, 0);
2890                                                         glNormal3fv(ln[0]);
2891                                                         glVertex3fv(aco);
2892
2893                                                         ln += 4;
2894                                                         a++;
2895                                                 }
2896                                         }
2897                                         glEnd();
2898                                 }
2899                                 else if (drawSmooth) {
2900                                         for (y = 0; y < gridFaces; y++) {
2901                                                 glBegin(GL_QUAD_STRIP);
2902                                                 for (x = 0; x < gridFaces; x++) {
2903                                                         vda = CCG_grid_elem(&key, faceGridData, x, y + 0);
2904                                                         vdb = CCG_grid_elem(&key, faceGridData, x, y + 1);
2905
2906                                                         PASSATTRIB(0, 0, 0);
2907                                                         glNormal3fv(CCG_elem_no(&key, vda));
2908                                                         glVertex3fv(CCG_elem_co(&key, vda));
2909
2910                                                         PASSATTRIB(0, 1, 1);
2911                                                         glNormal3fv(CCG_elem_no(&key, vdb));
2912                                                         glVertex3fv(CCG_elem_co(&key, vdb));
2913
2914                                                         if (x != gridFaces - 1)
2915                                                                 a++;
2916                                                 }
2917
2918                                                 vda = CCG_grid_elem(&key, faceGridData, x, y + 0);
2919                                                 vdb = CCG_grid_elem(&key, faceGridData, x, y + 1);
2920
2921                                                 PASSATTRIB(0, 0, 3);
2922                                                 glNormal3fv(CCG_elem_no(&key, vda));
2923                                                 glVertex3fv(CCG_elem_co(&key, vda));
2924
2925                                                 PASSATTRIB(0, 1, 2);
2926                                                 glNormal3fv(CCG_elem_no(&key, vdb));
2927                                                 glVertex3fv(CCG_elem_co(&key, vdb));
2928
2929                                                 glEnd();
2930
2931                                                 a++;
2932                                         }
2933                                 }
2934                                 else {
2935                                         glBegin(GL_QUADS);
2936                                         for (y = 0; y < gridFaces; y++) {
2937                                                 for (x = 0; x < gridFaces; x++) {
2938                                                         float *aco = CCG_grid_elem_co(&key, faceGridData, x, y);
2939                                                         float *bco = CCG_grid_elem_co(&key, faceGridData, x + 1, y);
2940                                                         float *cco = CCG_grid_elem_co(&key, faceGridData, x + 1, y + 1);
2941                                                         float *dco = CCG_grid_elem_co(&key, faceGridData, x, y + 1);
2942
2943                                                         ccgDM_glNormalFast(aco, bco, cco, dco);
2944
2945                                                         PASSATTRIB(0, 1, 1);
2946                                                         glVertex3fv(dco);
2947