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