Cleanup: rename uvflag -> flag for dm drawing
[blender.git] / source / blender / editors / space_view3d / drawmesh.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) 2001-2002 by NaN Holding BV.
19  * All rights reserved.
20  *
21  * Contributor(s): Blender Foundation, full update, glsl support
22  *
23  * ***** END GPL LICENSE BLOCK *****
24  */
25
26 /** \file blender/editors/space_view3d/drawmesh.c
27  *  \ingroup spview3d
28  */
29
30 #include <string.h>
31 #include <math.h>
32
33 #include "MEM_guardedalloc.h"
34
35 #include "BLI_utildefines.h"
36 #include "BLI_bitmap.h"
37 #include "BLI_math.h"
38
39 #include "DNA_material_types.h"
40 #include "DNA_mesh_types.h"
41 #include "DNA_meshdata_types.h"
42 #include "DNA_node_types.h"
43 #include "DNA_object_types.h"
44 #include "DNA_property_types.h"
45 #include "DNA_scene_types.h"
46 #include "DNA_screen_types.h"
47 #include "DNA_view3d_types.h"
48
49 #include "BKE_DerivedMesh.h"
50 #include "BKE_global.h"
51 #include "BKE_image.h"
52 #include "BKE_material.h"
53 #include "BKE_paint.h"
54 #include "BKE_property.h"
55 #include "BKE_editmesh.h"
56 #include "BKE_scene.h"
57
58 #include "BIF_gl.h"
59 #include "BIF_glutil.h"
60
61 #include "UI_resources.h"
62
63 #include "GPU_draw.h"
64 #include "GPU_material.h"
65 #include "GPU_basic_shader.h"
66 #include "GPU_shader.h"
67
68 #include "RE_engine.h"
69
70 #include "ED_uvedit.h"
71
72 #include "view3d_intern.h"  /* own include */
73
74 /* user data structures for derived mesh callbacks */
75 typedef struct drawMeshFaceSelect_userData {
76         Mesh *me;
77         BLI_bitmap *edge_flags; /* pairs of edge options (visible, select) */
78 } drawMeshFaceSelect_userData;
79
80 typedef struct drawEMTFMapped_userData {
81         BMEditMesh *em;
82         bool has_mcol;
83         int cd_poly_tex_offset;
84         const MPoly *mpoly;
85         const MTexPoly *mtexpoly;
86 } drawEMTFMapped_userData;
87
88 typedef struct drawTFace_userData {
89         const Mesh *me;
90         const MPoly *mpoly;
91         const MTexPoly *mtexpoly;
92 } drawTFace_userData;
93
94 /**************************** Face Select Mode *******************************/
95
96 /* mainly to be less confusing */
97 BLI_INLINE int edge_vis_index(const int index) { return index * 2; }
98 BLI_INLINE int edge_sel_index(const int index) { return index * 2 + 1; }
99
100 static BLI_bitmap *get_tface_mesh_marked_edge_info(Mesh *me, bool draw_select_edges)
101 {
102         BLI_bitmap *bitmap_edge_flags = BLI_BITMAP_NEW(me->totedge * 2, __func__);
103         MPoly *mp;
104         MLoop *ml;
105         int i, j;
106         bool select_set;
107         
108         for (i = 0; i < me->totpoly; i++) {
109                 mp = &me->mpoly[i];
110
111                 if (!(mp->flag & ME_HIDE)) {
112                         select_set = (mp->flag & ME_FACE_SEL) != 0;
113
114                         ml = me->mloop + mp->loopstart;
115                         for (j = 0; j < mp->totloop; j++, ml++) {
116                                 if ((draw_select_edges == false) &&
117                                     (select_set && BLI_BITMAP_TEST(bitmap_edge_flags, edge_sel_index(ml->e))))
118                                 {
119                                         BLI_BITMAP_DISABLE(bitmap_edge_flags, edge_vis_index(ml->e));
120                                 }
121                                 else {
122                                         BLI_BITMAP_ENABLE(bitmap_edge_flags, edge_vis_index(ml->e));
123                                         if (select_set) {
124                                                 BLI_BITMAP_ENABLE(bitmap_edge_flags, edge_sel_index(ml->e));
125                                         }
126                                 }
127                         }
128                 }
129         }
130
131         return bitmap_edge_flags;
132 }
133
134
135 static DMDrawOption draw_mesh_face_select__setHiddenOpts(void *userData, int index)
136 {
137         drawMeshFaceSelect_userData *data = userData;
138         Mesh *me = data->me;
139
140         if (me->drawflag & ME_DRAWEDGES) {
141                 if ((BLI_BITMAP_TEST(data->edge_flags, edge_vis_index(index))))
142                         return DM_DRAW_OPTION_NORMAL;
143                 else
144                         return DM_DRAW_OPTION_SKIP;
145         }
146         else if (BLI_BITMAP_TEST(data->edge_flags, edge_sel_index(index)) &&
147                  BLI_BITMAP_TEST(data->edge_flags, edge_vis_index(index)))
148         {
149                 return DM_DRAW_OPTION_NORMAL;
150         }
151         else {
152                 return DM_DRAW_OPTION_SKIP;
153         }
154 }
155
156 static DMDrawOption draw_mesh_face_select__setSelectOpts(void *userData, int index)
157 {
158         drawMeshFaceSelect_userData *data = userData;
159         return (BLI_BITMAP_TEST(data->edge_flags, edge_sel_index(index)) &&
160                 BLI_BITMAP_TEST(data->edge_flags, edge_vis_index(index))) ? DM_DRAW_OPTION_NORMAL : DM_DRAW_OPTION_SKIP;
161 }
162
163 /* draws unselected */
164 static DMDrawOption draw_mesh_face_select__drawFaceOptsInv(void *userData, int index)
165 {
166         Mesh *me = (Mesh *)userData;
167
168         MPoly *mpoly = &me->mpoly[index];
169         if (!(mpoly->flag & ME_HIDE) && !(mpoly->flag & ME_FACE_SEL))
170                 return DM_DRAW_OPTION_NORMAL;
171         else
172                 return DM_DRAW_OPTION_SKIP;
173 }
174
175 void draw_mesh_face_select(RegionView3D *rv3d, Mesh *me, DerivedMesh *dm, bool draw_select_edges)
176 {
177         drawMeshFaceSelect_userData data;
178
179         data.me = me;
180         data.edge_flags = get_tface_mesh_marked_edge_info(me, draw_select_edges);
181
182         glEnable(GL_DEPTH_TEST);
183         ED_view3d_polygon_offset(rv3d, 1.0);
184
185         /* Draw (Hidden) Edges */
186         setlinestyle(1);
187         UI_ThemeColor(TH_EDGE_FACESEL);
188         dm->drawMappedEdges(dm, draw_mesh_face_select__setHiddenOpts, &data);
189         setlinestyle(0);
190
191         /* Draw Selected Faces */
192         if (me->drawflag & ME_DRAWFACES) {
193                 glEnable(GL_BLEND);
194                 glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
195                 /* dull unselected faces so as not to get in the way of seeing color */
196                 glColor4ub(96, 96, 96, 64);
197                 dm->drawMappedFaces(dm, draw_mesh_face_select__drawFaceOptsInv, NULL, NULL, (void *)me, DM_DRAW_SKIP_HIDDEN);
198                 glDisable(GL_BLEND);
199         }
200         
201         ED_view3d_polygon_offset(rv3d, 1.0);
202
203         /* Draw Stippled Outline for selected faces */
204         glColor3ub(255, 255, 255);
205         setlinestyle(1);
206         dm->drawMappedEdges(dm, draw_mesh_face_select__setSelectOpts, &data);
207         setlinestyle(0);
208
209         ED_view3d_polygon_offset(rv3d, 0.0);  /* resets correctly now, even after calling accumulated offsets */
210
211         MEM_freeN(data.edge_flags);
212 }
213
214 /***************************** Texture Drawing ******************************/
215
216 static Material *give_current_material_or_def(Object *ob, int matnr)
217 {
218         extern Material defmaterial;  /* render module abuse... */
219         Material *ma = give_current_material(ob, matnr);
220
221         return ma ? ma : &defmaterial;
222 }
223
224 /* Icky globals, fix with userdata parameter */
225
226 static struct TextureDrawState {
227         Object *ob;
228         Image *stencil; /* texture painting stencil */
229         Image *canvas;  /* texture painting canvas, for image mode */
230         bool use_game_mat;
231         int is_lit, is_tex;
232         int color_profile;
233         bool use_backface_culling;
234         bool two_sided_lighting;
235         unsigned char obcol[4];
236         bool is_texpaint;
237         bool texpaint_material; /* use material slots for texture painting */
238 } Gtexdraw = {NULL, NULL, NULL, false, 0, 0, 0, false, false, {0, 0, 0, 0}, false, false};
239
240 static bool set_draw_settings_cached(int clearcache, MTexPoly *texface, Material *ma, struct TextureDrawState gtexdraw)
241 {
242         static Material *c_ma;
243         static int c_textured;
244         static MTexPoly c_texface;
245         static int c_backculled;
246         static bool c_badtex;
247         static int c_lit;
248         static int c_has_texface;
249
250         int backculled = 1;
251         int alphablend = GPU_BLEND_SOLID;
252         int textured = 0;
253         int lit = 0;
254         int has_texface = texface != NULL;
255         bool need_set_tpage = false;
256         bool texpaint = ((gtexdraw.ob->mode & OB_MODE_TEXTURE_PAINT) != 0);
257
258         Image *ima = NULL;
259
260         if (ma != NULL) {
261                 if (ma->mode & MA_TRANSP) {
262                         alphablend = GPU_BLEND_ALPHA;
263                 }
264         }
265
266         if (clearcache) {
267                 c_textured = c_lit = c_backculled = -1;
268                 memset(&c_texface, 0, sizeof(c_texface));
269                 c_badtex = false;
270                 c_has_texface = -1;
271                 c_ma = NULL;
272         }
273         else {
274                 textured = gtexdraw.is_tex;
275         }
276
277         /* convert number of lights into boolean */
278         if (gtexdraw.is_lit) lit = 1;
279
280         backculled = gtexdraw.use_backface_culling;
281         if (ma) {
282                 if (ma->mode & MA_SHLESS) lit = 0;
283                 if (gtexdraw.use_game_mat) {
284                         backculled = backculled || (ma->game.flag & GEMAT_BACKCULL);
285                         alphablend = ma->game.alpha_blend;
286                 }
287         }
288
289         if (texface && !texpaint) {
290                 textured = textured && (texface->tpage);
291
292                 /* no material, render alpha if texture has depth=32 */
293                 if (!ma && BKE_image_has_alpha(texface->tpage))
294                         alphablend = GPU_BLEND_ALPHA;
295         }
296         else if (texpaint) {
297                 if (gtexdraw.texpaint_material)
298                         ima = ma && ma->texpaintslot ? ma->texpaintslot[ma->paint_active_slot].ima : NULL;
299                 else
300                         ima = gtexdraw.canvas;
301         }
302         else
303                 textured = 0;
304
305         if (backculled != c_backculled) {
306                 if (backculled) glEnable(GL_CULL_FACE);
307                 else glDisable(GL_CULL_FACE);
308
309                 c_backculled = backculled;
310         }
311
312         /* need to re-set tpage if textured flag changed or existsment of texface changed..  */
313         need_set_tpage = textured != c_textured || has_texface != c_has_texface;
314         /* ..or if settings inside texface were changed (if texface was used) */
315         need_set_tpage |= (texpaint && c_ma != ma) || (texface && memcmp(&c_texface, texface, sizeof(c_texface)));
316
317         if (need_set_tpage) {
318                 if (textured) {
319                         if (texpaint) {
320                                 c_badtex = false;
321                                 if (GPU_verify_image(ima, NULL, GL_TEXTURE_2D, 0, 1, 0, false)) {
322                                         glEnable(GL_TEXTURE_2D);
323                                         glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_COMBINE);
324                                         glTexEnvi(GL_TEXTURE_ENV, GL_COMBINE_RGB, GL_MODULATE);
325                                         glTexEnvi(GL_TEXTURE_ENV, GL_SRC0_RGB, GL_TEXTURE);
326                                         glTexEnvi(GL_TEXTURE_ENV, GL_SRC1_RGB, GL_PRIMARY_COLOR);
327                                         glTexEnvi(GL_TEXTURE_ENV, GL_COMBINE_ALPHA, GL_REPLACE);
328                                         glTexEnvi(GL_TEXTURE_ENV, GL_SRC0_ALPHA, GL_TEXTURE);
329                                         
330                                         glActiveTexture(GL_TEXTURE1);
331                                         glEnable(GL_TEXTURE_2D);
332                                         glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_COMBINE);
333                                         glTexEnvi(GL_TEXTURE_ENV, GL_COMBINE_RGB, GL_INTERPOLATE);
334                                         glTexEnvi(GL_TEXTURE_ENV, GL_SRC0_RGB, GL_PREVIOUS);
335                                         glTexEnvi(GL_TEXTURE_ENV, GL_SRC1_RGB, GL_PRIMARY_COLOR);
336                                         glTexEnvi(GL_TEXTURE_ENV, GL_SRC2_RGB, GL_PREVIOUS);
337                                         glTexEnvi(GL_TEXTURE_ENV, GL_OPERAND2_RGB, GL_SRC_ALPHA);
338                                         glTexEnvi(GL_TEXTURE_ENV, GL_COMBINE_ALPHA, GL_REPLACE);
339                                         glTexEnvi(GL_TEXTURE_ENV, GL_SRC0_ALPHA, GL_PREVIOUS);
340                                         glBindTexture(GL_TEXTURE_2D, ima->bindcode[TEXTARGET_TEXTURE_2D]);
341                                         glActiveTexture(GL_TEXTURE0);                                   
342                                 }
343                                 else {
344                                         glActiveTexture(GL_TEXTURE1);
345                                         glDisable(GL_TEXTURE_2D);
346                                         glBindTexture(GL_TEXTURE_2D, 0);
347                                         glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);
348                                         glActiveTexture(GL_TEXTURE0);                                                                   
349
350                                         c_badtex = true;
351                                         GPU_clear_tpage(true);
352                                         glDisable(GL_TEXTURE_2D);
353                                         glBindTexture(GL_TEXTURE_2D, 0);
354                                         glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);
355                                 }
356                         }
357                         else {
358                                 c_badtex = !GPU_set_tpage(texface, !texpaint, alphablend);
359                         }
360                 }
361                 else {
362                         GPU_set_tpage(NULL, 0, 0);
363                         c_badtex = false;
364                 }
365                 c_textured = textured;
366                 c_has_texface = has_texface;
367                 if (texface)
368                         memcpy(&c_texface, texface, sizeof(c_texface));
369         }
370
371         if (c_badtex) lit = 0;
372         if (lit != c_lit || ma != c_ma) {
373                 if (lit) {
374                         int options = GPU_SHADER_LIGHTING | GPU_SHADER_USE_COLOR;
375
376                         if (gtexdraw.two_sided_lighting)
377                                 options |= GPU_SHADER_TWO_SIDED;
378                         if (c_textured && !c_badtex)
379                                 options |= GPU_SHADER_TEXTURE_2D;
380
381                         if (!ma)
382                                 ma = give_current_material_or_def(NULL, 0);  /* default material */
383
384                         float specular[3];
385                         mul_v3_v3fl(specular, &ma->specr, ma->spec);
386
387                         GPU_basic_shader_colors(NULL, specular, ma->har, 1.0f);
388                         GPU_basic_shader_bind(options);
389                 }
390                 else {
391                         GPU_basic_shader_bind(GPU_SHADER_USE_COLOR);
392                 }
393
394                 c_lit = lit;
395                 c_ma = ma;
396         }
397
398         return c_badtex;
399 }
400
401 static void draw_textured_begin(Scene *scene, View3D *v3d, RegionView3D *rv3d, Object *ob)
402 {
403         unsigned char obcol[4];
404         bool is_tex, solidtex;
405         Mesh *me = ob->data;
406         ImagePaintSettings *imapaint = &scene->toolsettings->imapaint;
407
408         /* XXX scene->obedit warning */
409
410         /* texture draw is abused for mask selection mode, do this so wire draw
411          * with face selection in weight paint is not lit. */
412         if ((v3d->drawtype <= OB_WIRE) && (ob->mode & (OB_MODE_VERTEX_PAINT | OB_MODE_WEIGHT_PAINT))) {
413                 solidtex = false;
414                 Gtexdraw.is_lit = 0;
415         }
416         else if ((ob->mode & OB_MODE_TEXTURE_PAINT) && BKE_scene_use_new_shading_nodes(scene)) {
417                 solidtex = true;
418                 if (v3d->flag2 & V3D_SHADELESS_TEX)
419                         Gtexdraw.is_lit = 0;
420                 else
421                         Gtexdraw.is_lit = -1;
422         }
423         else if ((v3d->drawtype == OB_SOLID) ||
424                  ((ob->mode & OB_MODE_EDIT) && (v3d->drawtype != OB_TEXTURE)))
425         {
426                 /* draw with default lights in solid draw mode and edit mode */
427                 solidtex = true;
428                 Gtexdraw.is_lit = -1;
429         }
430         else {
431                 /* draw with lights in the scene otherwise */
432                 solidtex = false;
433                 if (v3d->flag2 & V3D_SHADELESS_TEX)
434                         Gtexdraw.is_lit = 0;
435                 else
436                         Gtexdraw.is_lit = GPU_scene_object_lights(scene, ob, v3d->lay, rv3d->viewmat, !rv3d->is_persp);
437         }
438         
439         rgba_float_to_uchar(obcol, ob->col);
440
441         if (solidtex || v3d->drawtype == OB_TEXTURE) is_tex = true;
442         else is_tex = false;
443
444         Gtexdraw.ob = ob;
445         Gtexdraw.stencil = (imapaint->flag & IMAGEPAINT_PROJECT_LAYER_STENCIL) ? imapaint->stencil : NULL;
446         Gtexdraw.is_texpaint = (ob->mode == OB_MODE_TEXTURE_PAINT);
447         Gtexdraw.texpaint_material = (imapaint->mode == IMAGEPAINT_MODE_MATERIAL);
448         Gtexdraw.canvas = (Gtexdraw.texpaint_material) ? NULL : imapaint->canvas;
449         Gtexdraw.is_tex = is_tex;
450
451         /* naughty multitexturing hacks to quickly support stencil + shading + alpha blending 
452          * in new texpaint code. The better solution here would be to support GLSL */
453         if (Gtexdraw.is_texpaint) {                     
454                 glActiveTexture(GL_TEXTURE1);
455                 glEnable(GL_TEXTURE_2D);
456                 glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_COMBINE);
457                 glTexEnvi(GL_TEXTURE_ENV, GL_COMBINE_RGB, GL_INTERPOLATE);
458                 glTexEnvi(GL_TEXTURE_ENV, GL_SRC0_RGB, GL_PREVIOUS);
459                 glTexEnvi(GL_TEXTURE_ENV, GL_SRC1_RGB, GL_PRIMARY_COLOR);
460                 glTexEnvi(GL_TEXTURE_ENV, GL_SRC2_RGB, GL_PREVIOUS);
461                 glTexEnvi(GL_TEXTURE_ENV, GL_OPERAND2_RGB, GL_SRC_ALPHA);
462                 glTexEnvi(GL_TEXTURE_ENV, GL_COMBINE_ALPHA, GL_REPLACE);
463                 glTexEnvi(GL_TEXTURE_ENV, GL_SRC0_ALPHA, GL_PREVIOUS);
464                 
465                 /* load the stencil texture here */
466                 if (Gtexdraw.stencil != NULL) {
467                         glActiveTexture(GL_TEXTURE2);
468                         if (GPU_verify_image(Gtexdraw.stencil, NULL, GL_TEXTURE_2D, false, false, false, false)) {
469                                 float col[4] = {imapaint->stencil_col[0], imapaint->stencil_col[1], imapaint->stencil_col[2], 1.0f};
470                                 glEnable(GL_TEXTURE_2D);
471                                 glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_COMBINE);
472                                 glTexEnvi(GL_TEXTURE_ENV, GL_COMBINE_RGB, GL_INTERPOLATE);
473                                 glTexEnvi(GL_TEXTURE_ENV, GL_SRC0_RGB, GL_PREVIOUS);
474                                 glTexEnvi(GL_TEXTURE_ENV, GL_SRC1_RGB, GL_CONSTANT);
475                                 glTexEnvi(GL_TEXTURE_ENV, GL_SRC2_RGB, GL_TEXTURE);
476                                 glTexEnvi(GL_TEXTURE_ENV, GL_COMBINE_ALPHA, GL_MODULATE);
477                                 glTexEnvi(GL_TEXTURE_ENV, GL_SRC0_ALPHA, GL_PREVIOUS);
478                                 glTexEnvi(GL_TEXTURE_ENV, GL_SRC1_ALPHA, GL_TEXTURE);
479                                 glTexEnvfv(GL_TEXTURE_ENV, GL_TEXTURE_ENV_COLOR, col);
480                                 if ((imapaint->flag & IMAGEPAINT_PROJECT_LAYER_STENCIL_INV) == 0) {
481                                         glTexEnvi(GL_TEXTURE_ENV, GL_OPERAND2_RGB, GL_ONE_MINUS_SRC_COLOR);
482                                 }
483                                 else {
484                                         glTexEnvi(GL_TEXTURE_ENV, GL_OPERAND2_RGB, GL_SRC_COLOR);
485                                 }
486                         }
487                 }
488                 glActiveTexture(GL_TEXTURE0);
489         }
490         
491         Gtexdraw.color_profile = BKE_scene_check_color_management_enabled(scene);
492         Gtexdraw.use_game_mat = (RE_engines_find(scene->r.engine)->flag & RE_GAME) != 0;
493         Gtexdraw.use_backface_culling = (v3d->flag2 & V3D_BACKFACE_CULLING) != 0;
494         Gtexdraw.two_sided_lighting = (me->flag & ME_TWOSIDED);
495
496         memcpy(Gtexdraw.obcol, obcol, sizeof(obcol));
497         set_draw_settings_cached(1, NULL, NULL, Gtexdraw);
498         glShadeModel(GL_SMOOTH);
499         glCullFace(GL_BACK);
500 }
501
502 static void draw_textured_end(void)
503 {
504         if (Gtexdraw.ob->mode & OB_MODE_TEXTURE_PAINT) {
505                 glActiveTexture(GL_TEXTURE1);
506                 glDisable(GL_TEXTURE_2D);
507                 glTexEnvi(GL_TEXTURE_ENV, GL_OPERAND2_RGB, GL_SRC_COLOR);
508                 glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);
509                 glBindTexture(GL_TEXTURE_2D, 0);
510
511                 if (Gtexdraw.stencil != NULL) {
512                         glActiveTexture(GL_TEXTURE2);
513                         glDisable(GL_TEXTURE_2D);
514                         glTexEnvi(GL_TEXTURE_ENV, GL_OPERAND2_RGB, GL_SRC_COLOR);
515                         glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);
516                         glBindTexture(GL_TEXTURE_2D, 0);
517                 }               
518                 glActiveTexture(GL_TEXTURE0);
519                 glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);
520                 /* manual reset, since we don't use tpage */
521                 glBindTexture(GL_TEXTURE_2D, 0);
522                 /* force switch off textures */
523                 GPU_clear_tpage(true);
524         }
525         else {
526                 /* switch off textures */
527                 GPU_set_tpage(NULL, 0, 0);
528         }
529
530         glShadeModel(GL_FLAT);
531         glDisable(GL_CULL_FACE);
532         GPU_basic_shader_bind(GPU_SHADER_USE_COLOR);
533
534         /* XXX, bad patch - GPU_default_lights() calls
535          * glLightfv(GL_POSITION, ...) which
536          * is transformed by the current matrix... we
537          * need to make sure that matrix is identity.
538          * 
539          * It would be better if drawmesh.c kept track
540          * of and restored the light settings it changed.
541          *  - zr
542          */
543         glPushMatrix();
544         glLoadIdentity();
545         GPU_default_lights();
546         glPopMatrix();
547 }
548
549 static DMDrawOption draw_tface__set_draw_legacy(MTexPoly *mtexpoly, const bool has_mcol, int matnr)
550 {
551         Material *ma = give_current_material(Gtexdraw.ob, matnr + 1);
552         bool invalidtexture = false;
553
554         if (ma && (ma->game.flag & GEMAT_INVISIBLE))
555                 return DM_DRAW_OPTION_SKIP;
556
557         invalidtexture = set_draw_settings_cached(0, mtexpoly, ma, Gtexdraw);
558
559         if (mtexpoly && invalidtexture) {
560                 glColor3ub(0xFF, 0x00, 0xFF);
561                 return DM_DRAW_OPTION_NO_MCOL; /* Don't set color */
562         }
563         else if (!has_mcol) {
564                 if (mtexpoly) {
565                         glColor3f(1.0, 1.0, 1.0);
566                 }
567                 else {
568                         if (ma) {
569                                 if (ma->shade_flag & MA_OBCOLOR) {
570                                         glColor3ubv(Gtexdraw.obcol);
571                                 }
572                                 else {
573                                         float col[3];
574                                         if (Gtexdraw.color_profile) linearrgb_to_srgb_v3_v3(col, &ma->r);
575                                         else copy_v3_v3(col, &ma->r);
576
577                                         glColor3fv(col);
578                                 }
579                         }
580                         else {
581                                 glColor3f(1.0, 1.0, 1.0);
582                         }
583                 }
584                 return DM_DRAW_OPTION_NORMAL; /* normal drawing (no mcols anyway, no need to turn off) */
585         }
586         else {
587                 return DM_DRAW_OPTION_NORMAL; /* Set color from mcol */
588         }
589 }
590
591 static DMDrawOption draw_tface__set_draw(MTexPoly *mtexpoly, const bool UNUSED(has_mcol), int matnr)
592 {
593         Material *ma = give_current_material(Gtexdraw.ob, matnr + 1);
594
595         if (ma && (ma->game.flag & GEMAT_INVISIBLE)) return DM_DRAW_OPTION_SKIP;
596
597         if (mtexpoly || Gtexdraw.is_texpaint)
598                 set_draw_settings_cached(0, mtexpoly, ma, Gtexdraw);
599
600         /* always use color from mcol, as set in update_tface_color_layer */
601         return DM_DRAW_OPTION_NORMAL;
602 }
603
604 static void update_tface_color_layer(DerivedMesh *dm, bool use_mcol)
605 {
606         const MPoly *mp = dm->getPolyArray(dm);
607         const int mpoly_num = dm->getNumPolys(dm);
608         MTexPoly *mtexpoly = DM_get_poly_data_layer(dm, CD_MTEXPOLY);
609         MLoopCol *finalCol;
610         int i, j;
611         MLoopCol *mloopcol = NULL;
612
613         /* cache material values to avoid a lot of lookups */
614         Material *ma = NULL;
615         short mat_nr_prev = -1;
616         enum {
617                 COPY_CALC,
618                 COPY_ORIG,
619                 COPY_PREV,
620         } copy_mode = COPY_CALC;
621
622         if (use_mcol) {
623                 mloopcol = dm->getLoopDataArray(dm, CD_PREVIEW_MLOOPCOL);
624                 if (!mloopcol)
625                         mloopcol = dm->getLoopDataArray(dm, CD_MLOOPCOL);
626         }
627
628         if (CustomData_has_layer(&dm->loopData, CD_TEXTURE_MLOOPCOL)) {
629                 finalCol = CustomData_get_layer(&dm->loopData, CD_TEXTURE_MLOOPCOL);
630         }
631         else {
632                 finalCol = MEM_mallocN(sizeof(MLoopCol) * dm->numLoopData, "add_tface_color_layer");
633                 CustomData_add_layer(&dm->loopData, CD_TEXTURE_MLOOPCOL, CD_ASSIGN, finalCol, dm->numLoopData);
634         }
635
636         for (i = mpoly_num; i--; mp++) {
637                 const short mat_nr = mp->mat_nr;
638
639                 if (UNLIKELY(mat_nr_prev != mat_nr)) {
640                         ma = give_current_material(Gtexdraw.ob, mat_nr + 1);
641                         copy_mode = COPY_CALC;
642                         mat_nr_prev = mat_nr;
643                 }
644
645                 /* avoid lookups  */
646                 if (copy_mode == COPY_ORIG) {
647                         memcpy(&finalCol[mp->loopstart], &mloopcol[mp->loopstart], sizeof(*finalCol) * mp->totloop);
648                 }
649                 else if (copy_mode == COPY_PREV) {
650                         int loop_index = mp->loopstart;
651                         const MLoopCol *lcol_prev = &finalCol[(mp - 1)->loopstart];
652                         for (j = 0; j < mp->totloop; j++, loop_index++) {
653                                 finalCol[loop_index] = *lcol_prev;
654                         }
655                 }
656
657                 /* (copy_mode == COPY_CALC) */
658                 else if (ma && (ma->game.flag & GEMAT_INVISIBLE)) {
659                         if (mloopcol) {
660                                 memcpy(&finalCol[mp->loopstart], &mloopcol[mp->loopstart], sizeof(*finalCol) * mp->totloop);
661                                 copy_mode = COPY_ORIG;
662                         }
663                         else {
664                                 memset(&finalCol[mp->loopstart], 0xff, sizeof(*finalCol) * mp->totloop);
665                                 copy_mode = COPY_PREV;
666                         }
667                 }
668                 else if (mtexpoly && set_draw_settings_cached(0, mtexpoly, ma, Gtexdraw)) {
669                         int loop_index = mp->loopstart;
670                         for (j = 0; j < mp->totloop; j++, loop_index++) {
671                                 finalCol[loop_index].r = 255;
672                                 finalCol[loop_index].g = 0;
673                                 finalCol[loop_index].b = 255;
674                         }
675                         copy_mode = COPY_PREV;
676                 }
677                 else if (ma && (ma->shade_flag & MA_OBCOLOR)) {
678                         int loop_index = mp->loopstart;
679                         for (j = 0; j < mp->totloop; j++, loop_index++) {
680                                 copy_v3_v3_uchar(&finalCol[loop_index].r, Gtexdraw.obcol);
681                         }
682                         copy_mode = COPY_PREV;
683                 }
684                 else {
685                         if (mloopcol) {
686                                 memcpy(&finalCol[mp->loopstart], &mloopcol[mp->loopstart], sizeof(*finalCol) * mp->totloop);
687                                 copy_mode = COPY_ORIG;
688                         }
689                         else if (mtexpoly) {
690                                 memset(&finalCol[mp->loopstart], 0xff, sizeof(*finalCol) * mp->totloop);
691                                 copy_mode = COPY_PREV;
692                         }
693                         else {
694                                 float col[3];
695
696                                 if (ma) {
697                                         int loop_index = mp->loopstart;
698                                         MLoopCol lcol;
699
700                                         if (Gtexdraw.color_profile) linearrgb_to_srgb_v3_v3(col, &ma->r);
701                                         else copy_v3_v3(col, &ma->r);
702                                         rgb_float_to_uchar((unsigned char *)&lcol.r, col);
703                                         lcol.a = 255;
704                                         
705                                         for (j = 0; j < mp->totloop; j++, loop_index++) {
706                                                 finalCol[loop_index] = lcol;
707                                         }
708                                 }
709                                 else {
710                                         memset(&finalCol[mp->loopstart], 0xff, sizeof(*finalCol) * mp->totloop);
711                                 }
712                                 copy_mode = COPY_PREV;
713                         }
714                 }
715         }
716 }
717
718 static DMDrawOption draw_tface_mapped__set_draw(void *userData, int origindex, int UNUSED(mat_nr))
719 {
720         const Mesh *me = ((drawTFace_userData *)userData)->me;
721
722         /* array checked for NULL before calling */
723         MPoly *mpoly = &me->mpoly[origindex];
724
725         BLI_assert(origindex >= 0 && origindex < me->totpoly);
726
727         if (mpoly->flag & ME_HIDE) {
728                 return DM_DRAW_OPTION_SKIP;
729         }
730         else {
731                 MTexPoly *tpoly = (me->mtpoly) ? &me->mtpoly[origindex] : NULL;
732                 int matnr = mpoly->mat_nr;
733                 
734                 return draw_tface__set_draw(tpoly, (me->mloopcol != NULL), matnr);
735         }
736 }
737
738 static DMDrawOption draw_em_tf_mapped__set_draw(void *userData, int origindex, int mat_nr)
739 {
740         drawEMTFMapped_userData *data = userData;
741         BMEditMesh *em = data->em;
742         BMFace *efa;
743
744         if (UNLIKELY(origindex >= em->bm->totface))
745                 return DM_DRAW_OPTION_NORMAL;
746
747         efa = BM_face_at_index(em->bm, origindex);
748
749         if (BM_elem_flag_test(efa, BM_ELEM_HIDDEN)) {
750                 return DM_DRAW_OPTION_SKIP;
751         }
752         else {
753                 MTexPoly *mtexpoly = (data->cd_poly_tex_offset != -1) ?
754                         BM_ELEM_CD_GET_VOID_P(efa, data->cd_poly_tex_offset) : NULL;
755                 int matnr = (mat_nr != -1) ? mat_nr : efa->mat_nr;
756
757                 return draw_tface__set_draw_legacy(mtexpoly, data->has_mcol, matnr);
758         }
759 }
760
761 /* when face select is on, use face hidden flag */
762 static DMDrawOption wpaint__setSolidDrawOptions_facemask(void *userData, int index)
763 {
764         Mesh *me = (Mesh *)userData;
765         MPoly *mp = &me->mpoly[index];
766         if (mp->flag & ME_HIDE)
767                 return DM_DRAW_OPTION_SKIP;
768         return DM_DRAW_OPTION_NORMAL;
769 }
770
771 static void draw_mesh_text(Scene *scene, Object *ob, int glsl)
772 {
773         Mesh *me = ob->data;
774         DerivedMesh *ddm;
775         MPoly *mp, *mface  = me->mpoly;
776         MTexPoly *mtpoly   = me->mtpoly;
777         MLoopUV *mloopuv   = me->mloopuv;
778         MLoopUV *luv;
779         MLoopCol *mloopcol = me->mloopcol;  /* why does mcol exist? */
780         MLoopCol *lcol;
781
782         bProperty *prop = BKE_bproperty_object_get(ob, "Text");
783         GPUVertexAttribs gattribs;
784         int a, totpoly = me->totpoly;
785
786         /* fake values to pass to GPU_render_text() */
787         MCol  tmp_mcol[4]  = {{0}};
788         MCol *tmp_mcol_pt  = mloopcol ? tmp_mcol : NULL;
789
790         /* don't draw without tfaces */
791         if (!mtpoly || !mloopuv)
792                 return;
793
794         /* don't draw when editing */
795         if (ob->mode & OB_MODE_EDIT)
796                 return;
797         else if (ob == OBACT)
798                 if (BKE_paint_select_elem_test(ob))
799                         return;
800
801         ddm = mesh_get_derived_deform(scene, ob, CD_MASK_BAREMESH);
802
803         for (a = 0, mp = mface; a < totpoly; a++, mtpoly++, mp++) {
804                 short matnr = mp->mat_nr;
805                 const bool mf_smooth = (mp->flag & ME_SMOOTH) != 0;
806                 Material *mat = (me->mat) ? me->mat[matnr] : NULL;
807                 int mode = mat ? mat->game.flag : GEMAT_INVISIBLE;
808
809
810                 if (!(mode & GEMAT_INVISIBLE) && (mode & GEMAT_TEXT) && mp->totloop >= 3) {
811                         /* get the polygon as a tri/quad */
812                         int mp_vi[4];
813                         float   v_quad_data[4][3];
814                         const float  *v_quad[4];
815                         const float *uv_quad[4];
816                         char string[MAX_PROPSTRING];
817                         int characters, i, glattrib = -1, badtex = 0;
818
819
820                         /* TEXFACE */
821                         if (glsl) {
822                                 GPU_object_material_bind(matnr + 1, &gattribs);
823
824                                 for (i = 0; i < gattribs.totlayer; i++) {
825                                         if (gattribs.layer[i].type == CD_MTFACE) {
826                                                 glattrib = gattribs.layer[i].glindex;
827                                                 break;
828                                         }
829                                 }
830                         }
831                         else {
832                                 badtex = set_draw_settings_cached(0, mtpoly, mat, Gtexdraw);
833                                 if (badtex) {
834                                         continue;
835                                 }
836                         }
837
838                         mp_vi[0] = me->mloop[mp->loopstart + 0].v;
839                         mp_vi[1] = me->mloop[mp->loopstart + 1].v;
840                         mp_vi[2] = me->mloop[mp->loopstart + 2].v;
841                         mp_vi[3] = (mp->totloop >= 4) ? me->mloop[mp->loopstart + 3].v : 0;
842
843                         /* UV */
844                         luv = &mloopuv[mp->loopstart];
845                         uv_quad[0] = luv->uv; luv++;
846                         uv_quad[1] = luv->uv; luv++;
847                         uv_quad[2] = luv->uv; luv++;
848                         if (mp->totloop >= 4) {
849                                 uv_quad[3] = luv->uv;
850                         }
851                         else {
852                                 uv_quad[3] = NULL;
853                         }
854
855
856                         /* COLOR */
857                         if (mloopcol) {
858                                 unsigned int totloop_clamp = min_ii(4, mp->totloop);
859                                 unsigned int j;
860                                 lcol = &mloopcol[mp->loopstart];
861
862                                 for (j = 0; j < totloop_clamp; j++, lcol++) {
863                                         MESH_MLOOPCOL_TO_MCOL(lcol, &tmp_mcol[j]);
864                                 }
865                         }
866
867                         /* LOCATION */
868                         ddm->getVertCo(ddm, mp_vi[0], v_quad_data[0]);
869                         ddm->getVertCo(ddm, mp_vi[1], v_quad_data[1]);
870                         ddm->getVertCo(ddm, mp_vi[2], v_quad_data[2]);
871                         if (mp->totloop >= 4) {
872                                 ddm->getVertCo(ddm, mp_vi[3], v_quad_data[3]);
873                         }
874
875                         v_quad[0] = v_quad_data[0];
876                         v_quad[1] = v_quad_data[1];
877                         v_quad[2] = v_quad_data[2];
878                         if (mp->totloop >= 4) {
879                                 v_quad[3] = v_quad_data[2];
880                         }
881                         else {
882                                 v_quad[3] = NULL;
883                         }
884
885
886                         /* The BM_FONT handling is in the gpu module, shared with the
887                          * game engine, was duplicated previously */
888
889                         BKE_bproperty_set_valstr(prop, string);
890                         characters = strlen(string);
891                         
892                         if (!BKE_image_has_ibuf(mtpoly->tpage, NULL))
893                                 characters = 0;
894
895                         if (!mf_smooth) {
896                                 float nor[3];
897
898                                 normal_tri_v3(nor, v_quad[0], v_quad[1], v_quad[2]);
899
900                                 glNormal3fv(nor);
901                         }
902
903                         GPU_render_text(
904                                 mtpoly, mode, string, characters,
905                                 (unsigned int *)tmp_mcol_pt,
906                                 v_quad, uv_quad,
907                                 glattrib);
908                 }
909         }
910
911         ddm->release(ddm);
912 }
913
914 static int compareDrawOptions(void *userData, int cur_index, int next_index)
915 {
916         drawTFace_userData *data = userData;
917
918         if (data->mpoly && data->mpoly[cur_index].mat_nr != data->mpoly[next_index].mat_nr)
919                 return 0;
920
921         if (data->mtexpoly && data->mtexpoly[cur_index].tpage != data->mtexpoly[next_index].tpage)
922                 return 0;
923
924         return 1;
925 }
926
927
928 static int compareDrawOptionsEm(void *userData, int cur_index, int next_index)
929 {
930         drawEMTFMapped_userData *data = userData;
931
932         if (data->mpoly && data->mpoly[cur_index].mat_nr != data->mpoly[next_index].mat_nr)
933                 return 0;
934
935         if (data->mtexpoly && data->mtexpoly[cur_index].tpage != data->mtexpoly[next_index].tpage)
936                 return 0;
937
938         return 1;
939 }
940
941 static void draw_mesh_textured_old(Scene *scene, View3D *v3d, RegionView3D *rv3d,
942                                    Object *ob, DerivedMesh *dm, const int draw_flags)
943 {
944         Mesh *me = ob->data;
945
946         /* correct for negative scale */
947         if (ob->transflag & OB_NEG_SCALE) glFrontFace(GL_CW);
948         else glFrontFace(GL_CCW);
949         
950         /* draw the textured mesh */
951         draw_textured_begin(scene, v3d, rv3d, ob);
952
953         glColor4f(1.0f, 1.0f, 1.0f, 1.0f);
954
955         if (ob->mode & OB_MODE_EDIT) {
956                 drawEMTFMapped_userData data;
957
958                 data.em = me->edit_btmesh;
959                 data.has_mcol = CustomData_has_layer(&me->edit_btmesh->bm->ldata, CD_MLOOPCOL);
960                 data.cd_poly_tex_offset = CustomData_get_offset(&me->edit_btmesh->bm->pdata, CD_MTEXPOLY);
961
962                 data.mpoly = DM_get_poly_data_layer(dm, CD_MPOLY);
963                 data.mtexpoly = DM_get_poly_data_layer(dm, CD_MTEXPOLY);
964
965                 dm->drawMappedFacesTex(dm, draw_em_tf_mapped__set_draw, compareDrawOptionsEm, &data, 0);
966         }
967         else if ((draw_flags & DRAW_FACE_SELECT) &&
968                  (ob->mode & OB_MODE_WEIGHT_PAINT))
969         {
970                 dm->drawMappedFaces(dm, wpaint__setSolidDrawOptions_facemask, GPU_object_material_bind, NULL, me,
971                                     DM_DRAW_USE_COLORS | DM_DRAW_ALWAYS_SMOOTH | DM_DRAW_SKIP_HIDDEN);
972         }
973         else {
974                 DMDrawFlag dm_draw_flag;
975                 drawTFace_userData userData;
976
977                 if (ob->mode & OB_MODE_TEXTURE_PAINT) {
978                         dm_draw_flag = DM_DRAW_USE_TEXPAINT_UV;
979                 }
980                 else {
981                         dm_draw_flag = DM_DRAW_USE_ACTIVE_UV;
982                 }
983
984                 if ((ob->mode & OB_MODE_SCULPT) && (ob == OBACT)) {
985                         dm_draw_flag |= DM_DRAW_SKIP_HIDDEN;
986                 }
987
988
989                 userData.mpoly = DM_get_poly_data_layer(dm, CD_MPOLY);
990                 userData.mtexpoly = DM_get_poly_data_layer(dm, CD_MTEXPOLY);
991
992                 if (draw_flags & DRAW_FACE_SELECT) {
993                         userData.me = me;
994
995                         dm->drawMappedFacesTex(
996                                 dm, me->mpoly ? draw_tface_mapped__set_draw : NULL, compareDrawOptions,
997                                 &userData, dm_draw_flag);
998                 }
999                 else {
1000                         userData.me = NULL;
1001
1002                         update_tface_color_layer(dm, !(ob->mode & OB_MODE_TEXTURE_PAINT));
1003                         dm->drawFacesTex(
1004                                 dm, draw_tface__set_draw, compareDrawOptions,
1005                                 &userData, dm_draw_flag);
1006                 }
1007         }
1008
1009         /* draw game engine text hack */
1010         if (rv3d->rflag & RV3D_IS_GAME_ENGINE) {
1011                 if (BKE_bproperty_object_get(ob, "Text")) {
1012                         draw_mesh_text(scene, ob, 0);
1013                 }
1014         }
1015
1016         draw_textured_end();
1017         
1018         /* draw edges and selected faces over textured mesh */
1019         if (!(ob == scene->obedit) && (draw_flags & DRAW_FACE_SELECT)) {
1020                 bool draw_select_edges = (ob->mode & OB_MODE_TEXTURE_PAINT) == 0;
1021                 draw_mesh_face_select(rv3d, me, dm, draw_select_edges);
1022         }
1023
1024         /* reset from negative scale correction */
1025         glFrontFace(GL_CCW);
1026         
1027         /* in editmode, the blend mode needs to be set in case it was ADD */
1028         glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
1029 }
1030
1031 /************************** NEW SHADING NODES ********************************/
1032
1033 typedef struct TexMatCallback {
1034         Scene *scene;
1035         Object *ob;
1036         Mesh *me;
1037         DerivedMesh *dm;
1038         bool shadeless;
1039         bool two_sided_lighting;
1040 } TexMatCallback;
1041
1042 static void tex_mat_set_material_cb(void *UNUSED(userData), int mat_nr, void *attribs)
1043 {
1044         /* all we have to do here is simply enable the GLSL material, but note
1045          * that the GLSL code will give different result depending on the drawtype,
1046          * in texture draw mode it will output the active texture node, in material
1047          * draw mode it will show the full material. */
1048         GPU_object_material_bind(mat_nr, attribs);
1049 }
1050
1051 static void tex_mat_set_texture_cb(void *userData, int mat_nr, void *attribs)
1052 {
1053         /* texture draw mode without GLSL */
1054         TexMatCallback *data = (TexMatCallback *)userData;
1055         GPUVertexAttribs *gattribs = attribs;
1056         Image *ima;
1057         ImageUser *iuser;
1058         bNode *node;
1059
1060         /* draw image texture if we find one */
1061         if (ED_object_get_active_image(data->ob, mat_nr, &ima, &iuser, &node, NULL)) {
1062                 /* get openl texture */
1063                 int mipmap = 1;
1064                 int bindcode = (ima) ? GPU_verify_image(ima, iuser, GL_TEXTURE_2D, 0, 0, mipmap, false) : 0;
1065
1066                 if (bindcode) {
1067                         NodeTexBase *texbase = node->storage;
1068
1069                         /* disable existing material */
1070                         GPU_object_material_unbind();
1071
1072                         /* bind texture */
1073                         glBindTexture(GL_TEXTURE_2D, ima->bindcode[TEXTARGET_TEXTURE_2D]);
1074
1075                         glMatrixMode(GL_TEXTURE);
1076                         glLoadMatrixf(texbase->tex_mapping.mat);
1077                         glMatrixMode(GL_MODELVIEW);
1078
1079                         /* use active UV texture layer */
1080                         memset(gattribs, 0, sizeof(*gattribs));
1081
1082                         gattribs->layer[0].type = CD_MTFACE;
1083                         gattribs->layer[0].name[0] = '\0';
1084                         gattribs->layer[0].gltexco = 1;
1085                         gattribs->totlayer = 1;
1086
1087                         /* bind material */
1088                         float diffuse[3] = {1.0f, 1.0f, 1.0f};
1089
1090                         int options = GPU_SHADER_TEXTURE_2D;
1091                         if (!data->shadeless)
1092                                 options |= GPU_SHADER_LIGHTING;
1093                         if (data->two_sided_lighting)
1094                                 options |= GPU_SHADER_TWO_SIDED;
1095
1096                         GPU_basic_shader_colors(diffuse, NULL, 0, 1.0f);
1097                         GPU_basic_shader_bind(options);
1098
1099                         return;
1100                 }
1101         }
1102
1103         /* disable texture material */
1104         GPU_basic_shader_bind(GPU_SHADER_USE_COLOR);
1105
1106         if (data->shadeless) {
1107                 glColor3f(1.0f, 1.0f, 1.0f);
1108                 memset(gattribs, 0, sizeof(*gattribs));
1109         }
1110         else {
1111                 glMatrixMode(GL_TEXTURE);
1112                 glLoadIdentity();
1113                 glMatrixMode(GL_MODELVIEW);
1114
1115                 /* enable solid material */
1116                 GPU_object_material_bind(mat_nr, attribs);
1117         }
1118 }
1119
1120 static bool tex_mat_set_face_mesh_cb(void *userData, int index)
1121 {
1122         /* faceselect mode face hiding */
1123         TexMatCallback *data = (TexMatCallback *)userData;
1124         Mesh *me = (Mesh *)data->me;
1125         MPoly *mp = &me->mpoly[index];
1126
1127         return !(mp->flag & ME_HIDE);
1128 }
1129
1130 static bool tex_mat_set_face_editmesh_cb(void *userData, int index)
1131 {
1132         /* editmode face hiding */
1133         TexMatCallback *data = (TexMatCallback *)userData;
1134         Mesh *me = (Mesh *)data->me;
1135         BMEditMesh *em = me->edit_btmesh;
1136         BMFace *efa;
1137
1138         if (UNLIKELY(index >= em->bm->totface))
1139                 return DM_DRAW_OPTION_NORMAL;
1140
1141         efa = BM_face_at_index(em->bm, index);
1142
1143         return !BM_elem_flag_test(efa, BM_ELEM_HIDDEN);
1144 }
1145
1146 void draw_mesh_textured(Scene *scene, View3D *v3d, RegionView3D *rv3d,
1147                         Object *ob, DerivedMesh *dm, const int draw_flags)
1148 {
1149         /* if not cycles, or preview-modifiers, or drawing matcaps */
1150         if ((draw_flags & DRAW_MODIFIERS_PREVIEW) ||
1151             (v3d->flag2 & V3D_SHOW_SOLID_MATCAP) ||
1152             (BKE_scene_use_new_shading_nodes(scene) == false) ||
1153             ((ob->mode & OB_MODE_TEXTURE_PAINT) && ELEM(v3d->drawtype, OB_TEXTURE, OB_SOLID)))
1154         {
1155                 draw_mesh_textured_old(scene, v3d, rv3d, ob, dm, draw_flags);
1156                 return;
1157         }
1158         else if (ob->mode & (OB_MODE_VERTEX_PAINT | OB_MODE_WEIGHT_PAINT)) {
1159                 draw_mesh_paint(v3d, rv3d, ob, dm, draw_flags);
1160                 return;
1161         }
1162
1163         /* set opengl state for negative scale & color */
1164         if (ob->transflag & OB_NEG_SCALE) glFrontFace(GL_CW);
1165         else glFrontFace(GL_CCW);
1166
1167         Mesh *me = ob->data;
1168
1169         bool shadeless = ((v3d->flag2 & V3D_SHADELESS_TEX) &&
1170             ((v3d->drawtype == OB_TEXTURE) || (ob->mode & OB_MODE_TEXTURE_PAINT)));
1171         bool two_sided_lighting = (me->flag & ME_TWOSIDED) != 0;
1172
1173         TexMatCallback data = {scene, ob, me, dm, shadeless, two_sided_lighting};
1174         bool (*set_face_cb)(void *, int);
1175         bool picking = (G.f & G_PICKSEL) != 0;
1176         
1177         /* face hiding callback depending on mode */
1178         if (ob == scene->obedit)
1179                 set_face_cb = tex_mat_set_face_editmesh_cb;
1180         else if (draw_flags & DRAW_FACE_SELECT)
1181                 set_face_cb = tex_mat_set_face_mesh_cb;
1182         else
1183                 set_face_cb = NULL;
1184
1185         /* test if we can use glsl */
1186         bool glsl = (v3d->drawtype == OB_MATERIAL) && !picking;
1187
1188         GPU_begin_object_materials(v3d, rv3d, scene, ob, glsl, NULL);
1189
1190         if (glsl || picking) {
1191                 /* draw glsl or solid */
1192                 dm->drawMappedFacesMat(dm,
1193                                        tex_mat_set_material_cb,
1194                                        set_face_cb, &data);
1195         }
1196         else {
1197                 /* draw textured */
1198                 dm->drawMappedFacesMat(dm,
1199                                        tex_mat_set_texture_cb,
1200                                        set_face_cb, &data);
1201         }
1202
1203         GPU_end_object_materials();
1204
1205         /* reset opengl state */
1206         GPU_end_object_materials();
1207         GPU_basic_shader_bind(GPU_SHADER_USE_COLOR);
1208
1209         glBindTexture(GL_TEXTURE_2D, 0);
1210
1211         glFrontFace(GL_CCW);
1212
1213         glMatrixMode(GL_TEXTURE);
1214         glLoadIdentity();
1215         glMatrixMode(GL_MODELVIEW);
1216
1217         /* faceselect mode drawing over textured mesh */
1218         if (!(ob == scene->obedit) && (draw_flags & DRAW_FACE_SELECT)) {
1219                 bool draw_select_edges = (ob->mode & OB_MODE_TEXTURE_PAINT) == 0;
1220                 draw_mesh_face_select(rv3d, ob->data, dm, draw_select_edges);
1221         }
1222 }
1223
1224 /* Vertex Paint and Weight Paint */
1225 static void draw_mesh_paint_light_begin(void)
1226 {
1227         /* get material diffuse color from vertex colors but set default spec */
1228         const float specular[3] = {0.47f, 0.47f, 0.47f};
1229         GPU_basic_shader_colors(NULL, specular, 35, 1.0f);
1230         GPU_basic_shader_bind(GPU_SHADER_LIGHTING | GPU_SHADER_USE_COLOR);
1231 }
1232
1233 static void draw_mesh_paint_light_end(void)
1234 {
1235         GPU_basic_shader_bind(GPU_SHADER_USE_COLOR);
1236 }
1237
1238 void draw_mesh_paint_weight_faces(DerivedMesh *dm, const bool use_light,
1239                                   void *facemask_cb, void *user_data)
1240 {
1241         DMSetMaterial setMaterial = GPU_object_materials_check() ? GPU_object_material_bind : NULL;
1242         int flags = DM_DRAW_USE_COLORS;
1243
1244         if (use_light) {
1245                 draw_mesh_paint_light_begin();
1246                 flags |= DM_DRAW_NEED_NORMALS;
1247         }
1248
1249         dm->drawMappedFaces(dm, (DMSetDrawOptions)facemask_cb, setMaterial, NULL, user_data, flags);
1250
1251         if (use_light) {
1252                 draw_mesh_paint_light_end();
1253         }
1254 }
1255
1256 void draw_mesh_paint_vcolor_faces(DerivedMesh *dm, const bool use_light,
1257                                   void *facemask_cb, void *user_data,
1258                                   const Mesh *me)
1259 {
1260         DMSetMaterial setMaterial = GPU_object_materials_check() ? GPU_object_material_bind : NULL;
1261         int flags = 0;
1262
1263         if (use_light) {
1264                 draw_mesh_paint_light_begin();
1265                 flags |= DM_DRAW_NEED_NORMALS;
1266         }
1267
1268         if (me->mloopcol) {
1269                 dm->drawMappedFaces(dm, facemask_cb, setMaterial, NULL, user_data,
1270                                     DM_DRAW_USE_COLORS | flags);
1271         }
1272         else {
1273                 glColor3f(1.0f, 1.0f, 1.0f);
1274                 dm->drawMappedFaces(dm, facemask_cb, setMaterial, NULL, user_data, flags);
1275         }
1276
1277         if (use_light) {
1278                 draw_mesh_paint_light_end();
1279         }
1280 }
1281
1282 void draw_mesh_paint_weight_edges(RegionView3D *rv3d, DerivedMesh *dm,
1283                                   const bool use_depth, const bool use_alpha,
1284                                   void *edgemask_cb, void *user_data)
1285 {
1286         /* weight paint in solid mode, special case. focus on making the weights clear
1287          * rather than the shading, this is also forced in wire view */
1288
1289         if (use_depth) {
1290                 ED_view3d_polygon_offset(rv3d, 1.0);
1291                 glDepthMask(0);  /* disable write in zbuffer, selected edge wires show better */
1292         }
1293         else {
1294                 glDisable(GL_DEPTH_TEST);
1295         }
1296
1297         if (use_alpha) {
1298                 glEnable(GL_BLEND);
1299         }
1300
1301         glColor4ub(255, 255, 255, 96);
1302         glEnable(GL_LINE_STIPPLE);
1303         glLineStipple(1, 0xAAAA);
1304
1305         dm->drawMappedEdges(dm, (DMSetDrawOptions)edgemask_cb, user_data);
1306
1307         if (use_depth) {
1308                 ED_view3d_polygon_offset(rv3d, 0.0);
1309                 glDepthMask(1);
1310         }
1311         else {
1312                 glEnable(GL_DEPTH_TEST);
1313         }
1314
1315         glDisable(GL_LINE_STIPPLE);
1316
1317         if (use_alpha) {
1318                 glDisable(GL_BLEND);
1319         }
1320 }
1321
1322 void draw_mesh_paint(View3D *v3d, RegionView3D *rv3d,
1323                      Object *ob, DerivedMesh *dm, const int draw_flags)
1324 {
1325         DMSetDrawOptions facemask = NULL;
1326         Mesh *me = ob->data;
1327         const bool use_light = (v3d->drawtype >= OB_SOLID);
1328
1329         /* hide faces in face select mode */
1330         if (me->editflag & (ME_EDIT_PAINT_VERT_SEL | ME_EDIT_PAINT_FACE_SEL))
1331                 facemask = wpaint__setSolidDrawOptions_facemask;
1332
1333         if (ob->mode & OB_MODE_WEIGHT_PAINT) {
1334                 draw_mesh_paint_weight_faces(dm, use_light, facemask, me);
1335         }
1336         else if (ob->mode & OB_MODE_VERTEX_PAINT) {
1337                 draw_mesh_paint_vcolor_faces(dm, use_light, facemask, me, me);
1338         }
1339
1340         /* draw face selection on top */
1341         if (draw_flags & DRAW_FACE_SELECT) {
1342                 bool draw_select_edges = (ob->mode & OB_MODE_TEXTURE_PAINT) == 0;
1343                 draw_mesh_face_select(rv3d, me, dm, draw_select_edges);
1344         }
1345         else if ((use_light == false) || (ob->dtx & OB_DRAWWIRE)) {
1346                 const bool use_depth = (v3d->flag & V3D_ZBUF_SELECT) || !(ob->mode & OB_MODE_WEIGHT_PAINT);
1347                 const bool use_alpha = (ob->mode & OB_MODE_VERTEX_PAINT) == 0;
1348
1349                 if (use_alpha == false) {
1350                         set_inverted_drawing(1);
1351                 }
1352
1353                 draw_mesh_paint_weight_edges(rv3d, dm, use_depth, use_alpha, NULL, NULL);
1354
1355                 if (use_alpha == false) {
1356                         set_inverted_drawing(0);
1357                 }
1358         }
1359 }
1360