OpenSubdiv: Commit of OpenSubdiv integration into Blender
[blender.git] / source / blender / gpu / intern / gpu_draw.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): Brecht Van Lommel.
24  *
25  * ***** END GPL LICENSE BLOCK *****
26  */
27
28 /** \file blender/gpu/intern/gpu_draw.c
29  *  \ingroup gpu
30  *
31  * Utility functions for dealing with OpenGL texture & material context,
32  * mipmap generation and light objects.
33  *
34  * These are some obscure rendering functions shared between the
35  * game engine and the blender, in this module to avoid duplication
36  * and abstract them away from the rest a bit.
37  */
38
39 #include <string.h>
40
41 #include "GPU_glew.h"
42 #include "GPU_debug.h"
43
44 #include "BLI_blenlib.h"
45 #include "BLI_linklist.h"
46 #include "BLI_math.h"
47 #include "BLI_threads.h"
48 #include "BLI_utildefines.h"
49
50 #include "DNA_lamp_types.h"
51 #include "DNA_material_types.h"
52 #include "DNA_meshdata_types.h"
53 #include "DNA_modifier_types.h"
54 #include "DNA_node_types.h"
55 #include "DNA_object_types.h"
56 #include "DNA_scene_types.h"
57 #include "DNA_smoke_types.h"
58 #include "DNA_view3d_types.h"
59 #include "DNA_particle_types.h"
60
61 #include "MEM_guardedalloc.h"
62
63 #include "IMB_imbuf.h"
64 #include "IMB_imbuf_types.h"
65
66 #include "BKE_bmfont.h"
67 #include "BKE_global.h"
68 #include "BKE_image.h"
69 #include "BKE_main.h"
70 #include "BKE_material.h"
71 #include "BKE_node.h"
72 #include "BKE_object.h"
73 #include "BKE_scene.h"
74 #include "BKE_subsurf.h"
75 #include "BKE_DerivedMesh.h"
76
77 #include "GPU_buffers.h"
78 #include "GPU_draw.h"
79 #include "GPU_extensions.h"
80 #include "GPU_material.h"
81
82 #include "PIL_time.h"
83
84 #include "smoke_API.h"
85
86 #ifdef WITH_OPENSUBDIV
87 #  include "DNA_mesh_types.h"
88 #  include "BKE_editmesh.h"
89
90 #  include "gpu_codegen.h"
91 #endif
92
93 extern Material defmaterial; /* from material.c */
94
95 /* Text Rendering */
96
97 static void gpu_mcol(unsigned int ucol)
98 {
99         /* mcol order is swapped */
100         const char *cp = (char *)&ucol;
101         glColor3ub(cp[3], cp[2], cp[1]);
102 }
103
104 void GPU_render_text(
105         MTexPoly *mtexpoly, int mode,
106         const char *textstr, int textlen, unsigned int *col,
107         const float *v_quad[4], const float *uv_quad[4],
108         int glattrib)
109 {
110         if ((mode & GEMAT_TEXT) && (textlen > 0) && mtexpoly->tpage) {
111                 const float *v1 = v_quad[0];
112                 const float *v2 = v_quad[1];
113                 const float *v3 = v_quad[2];
114                 const float *v4 = v_quad[3];
115                 Image *ima = (Image *)mtexpoly->tpage;
116                 ImBuf *first_ibuf;
117                 const size_t textlen_st = textlen;
118                 size_t index;
119                 float centerx, centery, sizex, sizey, transx, transy, movex, movey, advance;
120                 float advance_tab;
121                 
122                 /* multiline */
123                 float line_start = 0.0f, line_height;
124                 
125                 if (v4)
126                         line_height = max_ffff(v1[1], v2[1], v3[1], v4[2]) - min_ffff(v1[1], v2[1], v3[1], v4[2]);
127                 else
128                         line_height = max_fff(v1[1], v2[1], v3[1]) - min_fff(v1[1], v2[1], v3[1]);
129                 line_height *= 1.2f; /* could be an option? */
130                 /* end multiline */
131
132                 
133                 /* color has been set */
134                 if (mtexpoly->mode & TF_OBCOL)
135                         col = NULL;
136                 else if (!col)
137                         glColor3f(1.0f, 1.0f, 1.0f);
138
139                 glPushMatrix();
140                 
141                 /* get the tab width */
142                 first_ibuf = BKE_image_get_first_ibuf(ima);
143                 matrixGlyph(first_ibuf, ' ', &centerx, &centery,
144                         &sizex, &sizey, &transx, &transy, &movex, &movey, &advance);
145                 
146                 advance_tab = advance * 4; /* tab width could also be an option */
147                 
148                 
149                 for (index = 0; index < textlen_st; ) {
150                         unsigned int character;
151                         float uv[4][2];
152
153                         /* lets calculate offset stuff */
154                         character = BLI_str_utf8_as_unicode_and_size_safe(textstr + index, &index);
155                         
156                         if (character == '\n') {
157                                 glTranslatef(line_start, -line_height, 0.0f);
158                                 line_start = 0.0f;
159                                 continue;
160                         }
161                         else if (character == '\t') {
162                                 glTranslatef(advance_tab, 0.0f, 0.0f);
163                                 line_start -= advance_tab; /* so we can go back to the start of the line */
164                                 continue;
165                                 
166                         }
167                         else if (character > USHRT_MAX) {
168                                 /* not much we can do here bmfonts take ushort */
169                                 character = '?';
170                         }
171                         
172                         /* space starts at offset 1 */
173                         /* character = character - ' ' + 1; */
174                         matrixGlyph(first_ibuf, character, & centerx, &centery,
175                                 &sizex, &sizey, &transx, &transy, &movex, &movey, &advance);
176
177                         uv[0][0] = (uv_quad[0][0] - centerx) * sizex + transx;
178                         uv[0][1] = (uv_quad[0][1] - centery) * sizey + transy;
179                         uv[1][0] = (uv_quad[1][0] - centerx) * sizex + transx;
180                         uv[1][1] = (uv_quad[1][1] - centery) * sizey + transy;
181                         uv[2][0] = (uv_quad[2][0] - centerx) * sizex + transx;
182                         uv[2][1] = (uv_quad[2][1] - centery) * sizey + transy;
183                         
184                         glBegin(GL_POLYGON);
185                         if (glattrib >= 0) glVertexAttrib2fvARB(glattrib, uv[0]);
186                         else glTexCoord2fv(uv[0]);
187                         if (col) gpu_mcol(col[0]);
188                         glVertex3f(sizex * v1[0] + movex, sizey * v1[1] + movey, v1[2]);
189                         
190                         if (glattrib >= 0) glVertexAttrib2fvARB(glattrib, uv[1]);
191                         else glTexCoord2fv(uv[1]);
192                         if (col) gpu_mcol(col[1]);
193                         glVertex3f(sizex * v2[0] + movex, sizey * v2[1] + movey, v2[2]);
194
195                         if (glattrib >= 0) glVertexAttrib2fvARB(glattrib, uv[2]);
196                         else glTexCoord2fv(uv[2]);
197                         if (col) gpu_mcol(col[2]);
198                         glVertex3f(sizex * v3[0] + movex, sizey * v3[1] + movey, v3[2]);
199
200                         if (v4) {
201                                 uv[3][0] = (uv_quad[3][0] - centerx) * sizex + transx;
202                                 uv[3][1] = (uv_quad[3][1] - centery) * sizey + transy;
203
204                                 if (glattrib >= 0) glVertexAttrib2fvARB(glattrib, uv[3]);
205                                 else glTexCoord2fv(uv[3]);
206                                 if (col) gpu_mcol(col[3]);
207                                 glVertex3f(sizex * v4[0] + movex, sizey * v4[1] + movey, v4[2]);
208                         }
209                         glEnd();
210
211                         glTranslatef(advance, 0.0f, 0.0f);
212                         line_start -= advance; /* so we can go back to the start of the line */
213                 }
214                 glPopMatrix();
215
216                 BKE_image_release_ibuf(ima, first_ibuf, NULL);
217         }
218 }
219
220 /* Checking powers of two for images since opengl 1.x requires it */
221
222 static bool is_power_of_2_resolution(int w, int h)
223 {
224         return is_power_of_2_i(w) && is_power_of_2_i(h);
225 }
226
227 static bool is_over_resolution_limit(int w, int h)
228 {
229         int reslimit = (U.glreslimit != 0)?
230                 min_ii(U.glreslimit, GPU_max_texture_size()) :
231                 GPU_max_texture_size();
232
233         return (w > reslimit || h > reslimit);
234 }
235
236 static int smaller_power_of_2_limit(int num)
237 {
238         int reslimit = (U.glreslimit != 0)?
239                 min_ii(U.glreslimit, GPU_max_texture_size()) :
240                 GPU_max_texture_size();
241         /* take texture clamping into account */
242         if (num > reslimit)
243                 return reslimit;
244
245         return power_of_2_min_i(num);
246 }
247
248 /* Current OpenGL state caching for GPU_set_tpage */
249
250 static struct GPUTextureState {
251         int curtile, tile;
252         int curtilemode, tilemode;
253         int curtileXRep, tileXRep;
254         int curtileYRep, tileYRep;
255         Image *ima, *curima;
256
257         /* also controls min/mag filtering */
258         bool domipmap;
259         /* only use when 'domipmap' is set */
260         bool linearmipmap;
261         /* store this so that new images created while texture painting won't be set to mipmapped */
262         bool texpaint;
263
264         int alphablend;
265         float anisotropic;
266         int gpu_mipmap;
267         MTexPoly *lasttface;
268 } GTS = {0, 0, 0, 0, 0, 0, 0, 0, NULL, NULL, 1, 0, 0, -1, 1.0f, 0, NULL};
269
270 /* Mipmap settings */
271
272 void GPU_set_gpu_mipmapping(int gpu_mipmap)
273 {
274         int old_value = GTS.gpu_mipmap;
275
276         /* only actually enable if it's supported */
277         GTS.gpu_mipmap = gpu_mipmap && GLEW_EXT_framebuffer_object;
278
279         if (old_value != GTS.gpu_mipmap) {
280                 GPU_free_images();
281         }
282 }
283
284 static void gpu_generate_mipmap(GLenum target)
285 {
286         const bool is_ati = GPU_type_matches(GPU_DEVICE_ATI, GPU_OS_ANY, GPU_DRIVER_ANY);
287         int target_enabled = 0;
288
289         /* work around bug in ATI driver, need to have GL_TEXTURE_2D enabled
290          * http://www.opengl.org/wiki/Common_Mistakes#Automatic_mipmap_generation */
291         if (is_ati) {
292                 target_enabled = glIsEnabled(target);
293                 if (!target_enabled)
294                         glEnable(target);
295         }
296
297         glGenerateMipmapEXT(target);
298
299         if (is_ati && !target_enabled)
300                 glDisable(target);
301 }
302
303 void GPU_set_mipmap(bool mipmap)
304 {
305         if (GTS.domipmap != mipmap) {
306                 GPU_free_images();
307                 GTS.domipmap = mipmap;
308         }
309 }
310
311 void GPU_set_linear_mipmap(bool linear)
312 {
313         if (GTS.linearmipmap != linear) {
314                 GTS.linearmipmap = linear;
315         }
316 }
317
318 bool GPU_get_mipmap(void)
319 {
320         return GTS.domipmap && !GTS.texpaint;
321 }
322
323 bool GPU_get_linear_mipmap(void)
324 {
325         return GTS.linearmipmap;
326 }
327
328 static GLenum gpu_get_mipmap_filter(bool mag)
329 {
330         /* linearmipmap is off by default *when mipmapping is off,
331          * use unfiltered display */
332         if (mag) {
333                 if (GTS.domipmap)
334                         return GL_LINEAR;
335                 else
336                         return GL_NEAREST;
337         }
338         else {
339                 if (GTS.domipmap) {
340                         if (GTS.linearmipmap) {
341                                 return GL_LINEAR_MIPMAP_LINEAR;
342                         }
343                         else {
344                                 return GL_LINEAR_MIPMAP_NEAREST;
345                         }
346                 }
347                 else {
348                         return GL_NEAREST;
349                 }
350         }
351 }
352
353 /* Anisotropic filtering settings */
354 void GPU_set_anisotropic(float value)
355 {
356         if (GTS.anisotropic != value) {
357                 GPU_free_images();
358
359                 /* Clamp value to the maximum value the graphics card supports */
360                 if (value > GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT)
361                         value = GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT;
362
363                 GTS.anisotropic = value;
364         }
365 }
366
367 float GPU_get_anisotropic(void)
368 {
369         return GTS.anisotropic;
370 }
371
372 /* Set OpenGL state for an MTFace */
373
374 static void gpu_make_repbind(Image *ima)
375 {
376         ImBuf *ibuf;
377         
378         ibuf = BKE_image_acquire_ibuf(ima, NULL, NULL);
379         if (ibuf == NULL)
380                 return;
381
382         if (ima->repbind) {
383                 glDeleteTextures(ima->totbind, (GLuint *)ima->repbind);
384                 MEM_freeN(ima->repbind);
385                 ima->repbind = NULL;
386                 ima->tpageflag &= ~IMA_MIPMAP_COMPLETE;
387         }
388
389         ima->totbind = ima->xrep*ima->yrep;
390
391         if (ima->totbind>1)
392                 ima->repbind = MEM_callocN(sizeof(int) * ima->totbind, "repbind");
393
394         BKE_image_release_ibuf(ima, ibuf, NULL);
395 }
396
397 void GPU_clear_tpage(bool force)
398 {
399         if (GTS.lasttface == NULL && !force)
400                 return;
401         
402         GTS.lasttface = NULL;
403         GTS.curtile = 0;
404         GTS.curima = NULL;
405         if (GTS.curtilemode != 0) {
406                 glMatrixMode(GL_TEXTURE);
407                 glLoadIdentity();
408                 glMatrixMode(GL_MODELVIEW);
409         }
410         GTS.curtilemode = 0;
411         GTS.curtileXRep = 0;
412         GTS.curtileYRep = 0;
413         GTS.alphablend = -1;
414         
415         glDisable(GL_BLEND);
416         glDisable(GL_TEXTURE_2D);
417         glDisable(GL_TEXTURE_GEN_S);
418         glDisable(GL_TEXTURE_GEN_T);
419         glDisable(GL_ALPHA_TEST);
420 }
421
422 static void gpu_set_alpha_blend(GPUBlendMode alphablend)
423 {
424         if (alphablend == GPU_BLEND_SOLID) {
425                 glDisable(GL_BLEND);
426                 glDisable(GL_ALPHA_TEST);
427                 glDisable(GL_SAMPLE_ALPHA_TO_COVERAGE);
428                 glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
429         }
430         else if (alphablend == GPU_BLEND_ADD) {
431                 glEnable(GL_BLEND);
432                 glBlendFunc(GL_ONE, GL_ONE);
433                 glDisable(GL_ALPHA_TEST);
434                 glDisable(GL_SAMPLE_ALPHA_TO_COVERAGE);
435         }
436         else if (ELEM(alphablend, GPU_BLEND_ALPHA, GPU_BLEND_ALPHA_SORT)) {
437                 glEnable(GL_BLEND);
438                 glDisable(GL_SAMPLE_ALPHA_TO_COVERAGE);
439
440                 /* for OpenGL render we use the alpha channel, this makes alpha blend correct */
441                 if (GLEW_VERSION_1_4)
442                         glBlendFuncSeparate(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, GL_ONE, GL_ONE_MINUS_SRC_ALPHA);
443                 else
444                         glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
445                 
446                 /* if U.glalphaclip == 1.0, some cards go bonkers...
447                  * turn off alpha test in this case */
448
449                 /* added after 2.45 to clip alpha */
450                 if (U.glalphaclip == 1.0f) {
451                         glDisable(GL_ALPHA_TEST);
452                 }
453                 else {
454                         glEnable(GL_ALPHA_TEST);
455                         glAlphaFunc(GL_GREATER, U.glalphaclip);
456                 }
457         }
458         else if (alphablend == GPU_BLEND_CLIP) {
459                 glDisable(GL_BLEND);
460                 glDisable(GL_SAMPLE_ALPHA_TO_COVERAGE);
461                 glEnable(GL_ALPHA_TEST);
462                 glAlphaFunc(GL_GREATER, 0.5f);
463         }
464         else if (alphablend == GPU_BLEND_ALPHA_TO_COVERAGE) {
465                 glEnable(GL_ALPHA_TEST);
466                 glAlphaFunc(GL_GREATER, U.glalphaclip);
467                 glEnable(GL_SAMPLE_ALPHA_TO_COVERAGE);
468         }
469 }
470
471 static void gpu_verify_alpha_blend(int alphablend)
472 {
473         /* verify alpha blending modes */
474         if (GTS.alphablend == alphablend)
475                 return;
476
477         gpu_set_alpha_blend(alphablend);
478         GTS.alphablend = alphablend;
479 }
480
481 static void gpu_verify_reflection(Image *ima)
482 {
483         if (ima && (ima->flag & IMA_REFLECT)) {
484                 /* enable reflection mapping */
485                 glTexGeni(GL_S, GL_TEXTURE_GEN_MODE, GL_SPHERE_MAP);
486                 glTexGeni(GL_T, GL_TEXTURE_GEN_MODE, GL_SPHERE_MAP);
487
488                 glEnable(GL_TEXTURE_GEN_S);
489                 glEnable(GL_TEXTURE_GEN_T);
490         }
491         else {
492                 /* disable reflection mapping */
493                 glDisable(GL_TEXTURE_GEN_S);
494                 glDisable(GL_TEXTURE_GEN_T);
495         }
496 }
497
498 int GPU_verify_image(Image *ima, ImageUser *iuser, int tftile, bool compare, bool mipmap, bool is_data)
499 {
500         ImBuf *ibuf = NULL;
501         unsigned int *bind = NULL;
502         int rectw, recth, tpx = 0, tpy = 0, y;
503         unsigned int *tilerect = NULL, *rect = NULL;
504         float *ftilerect = NULL, *frect = NULL;
505         float *srgb_frect = NULL;
506         short texwindx, texwindy, texwinsx, texwinsy;
507         /* flag to determine whether high resolution format is used */
508         bool use_high_bit_depth = false, do_color_management = false;
509
510         /* initialize tile mode and number of repeats */
511         GTS.ima = ima;
512         GTS.tilemode = (ima && (ima->tpageflag & (IMA_TILES|IMA_TWINANIM)));
513         GTS.tileXRep = 0;
514         GTS.tileYRep = 0;
515
516         /* setting current tile according to frame */
517         if (ima && (ima->tpageflag & IMA_TWINANIM))
518                 GTS.tile = ima->lastframe;
519         else
520                 GTS.tile = tftile;
521
522         GTS.tile = MAX2(0, GTS.tile);
523
524         if (ima) {
525                 GTS.tileXRep = ima->xrep;
526                 GTS.tileYRep = ima->yrep;
527         }
528
529         /* if same image & tile, we're done */
530         if (compare && ima == GTS.curima && GTS.curtile == GTS.tile &&
531             GTS.tilemode == GTS.curtilemode && GTS.curtileXRep == GTS.tileXRep &&
532             GTS.curtileYRep == GTS.tileYRep)
533         {
534                 return (ima != NULL);
535         }
536
537         /* if tiling mode or repeat changed, change texture matrix to fit */
538         if (GTS.tilemode != GTS.curtilemode || GTS.curtileXRep != GTS.tileXRep ||
539             GTS.curtileYRep != GTS.tileYRep)
540         {
541                 glMatrixMode(GL_TEXTURE);
542                 glLoadIdentity();
543
544                 if (ima && (ima->tpageflag & IMA_TILES))
545                         glScalef(ima->xrep, ima->yrep, 1.0f);
546
547                 glMatrixMode(GL_MODELVIEW);
548         }
549
550         /* check if we have a valid image */
551         if (ima == NULL || ima->ok == 0)
552                 return 0;
553
554         /* check if we have a valid image buffer */
555         ibuf = BKE_image_acquire_ibuf(ima, iuser, NULL);
556
557         if (ibuf == NULL)
558                 return 0;
559
560         if (ibuf->rect_float) {
561                 if (U.use_16bit_textures) {
562                         /* use high precision textures. This is relatively harmless because OpenGL gives us
563                          * a high precision format only if it is available */
564                         use_high_bit_depth = true;
565                 }
566                 /* we may skip this in high precision, but if not, we need to have a valid buffer here */
567                 else if (ibuf->userflags & IB_RECT_INVALID) {
568                         IMB_rect_from_float(ibuf);
569                 }
570
571                 /* TODO unneeded when float images are correctly treated as linear always */
572                 if (!is_data)
573                         do_color_management = true;
574
575                 if (ibuf->rect == NULL)
576                         IMB_rect_from_float(ibuf);
577         }
578
579         /* currently, tpage refresh is used by ima sequences */
580         if (ima->tpageflag & IMA_TPAGE_REFRESH) {
581                 GPU_free_image(ima);
582                 ima->tpageflag &= ~IMA_TPAGE_REFRESH;
583         }
584         
585         if (GTS.tilemode) {
586                 /* tiled mode */
587                 if (ima->repbind == NULL) gpu_make_repbind(ima);
588                 if (GTS.tile >= ima->totbind) GTS.tile = 0;
589                 
590                 /* this happens when you change repeat buttons */
591                 if (ima->repbind) bind = &ima->repbind[GTS.tile];
592                 else bind = &ima->bindcode;
593                 
594                 if (*bind == 0) {
595                         texwindx = ibuf->x / ima->xrep;
596                         texwindy = ibuf->y / ima->yrep;
597                         
598                         if (GTS.tile >= ima->xrep * ima->yrep)
599                                 GTS.tile = ima->xrep * ima->yrep - 1;
600         
601                         texwinsy = GTS.tile / ima->xrep;
602                         texwinsx = GTS.tile - texwinsy * ima->xrep;
603         
604                         texwinsx *= texwindx;
605                         texwinsy *= texwindy;
606         
607                         tpx = texwindx;
608                         tpy = texwindy;
609
610                         if (use_high_bit_depth) {
611                                 if (do_color_management) {
612                                         srgb_frect = MEM_mallocN(ibuf->x * ibuf->y * sizeof(float) * 4, "floar_buf_col_cor");
613                                         IMB_buffer_float_from_float(srgb_frect, ibuf->rect_float,
614                                                 ibuf->channels, IB_PROFILE_SRGB, IB_PROFILE_LINEAR_RGB, true,
615                                                 ibuf->x, ibuf->y, ibuf->x, ibuf->x);
616                                         IMB_buffer_float_unpremultiply(srgb_frect, ibuf->x, ibuf->y);
617                                         /* clamp buffer colors to 1.0 to avoid artifacts due to glu for hdr images */
618                                         IMB_buffer_float_clamp(srgb_frect, ibuf->x, ibuf->y);
619                                         frect = srgb_frect + texwinsy*ibuf->x + texwinsx;
620                                 }
621                                 else
622                                         frect = ibuf->rect_float + texwinsy*ibuf->x + texwinsx;
623                         }
624                         else
625                                 rect = ibuf->rect + texwinsy*ibuf->x + texwinsx;
626                 }
627         }
628         else {
629                 /* regular image mode */
630                 bind= &ima->bindcode;
631
632                 if (*bind == 0) {
633                         tpx = ibuf->x;
634                         tpy = ibuf->y;
635                         rect = ibuf->rect;
636                         if (use_high_bit_depth) {
637                                 if (do_color_management) {
638                                         frect = srgb_frect = MEM_mallocN(ibuf->x * ibuf->y * sizeof(*srgb_frect) * 4, "floar_buf_col_cor");
639                                         IMB_buffer_float_from_float(srgb_frect, ibuf->rect_float,
640                                                         ibuf->channels, IB_PROFILE_SRGB, IB_PROFILE_LINEAR_RGB, true,
641                                                         ibuf->x, ibuf->y, ibuf->x, ibuf->x);
642                                         IMB_buffer_float_unpremultiply(srgb_frect, ibuf->x, ibuf->y);
643                                         /* clamp buffer colors to 1.0 to avoid artifacts due to glu for hdr images */
644                                         IMB_buffer_float_clamp(srgb_frect, ibuf->x, ibuf->y);
645                                 }
646                                 else
647                                         frect = ibuf->rect_float;
648                         }
649                 }
650         }
651
652         if (*bind != 0) {
653                 /* enable opengl drawing with textures */
654                 glBindTexture(GL_TEXTURE_2D, *bind);
655                 BKE_image_release_ibuf(ima, ibuf, NULL);
656                 return *bind;
657         }
658
659         rectw = tpx;
660         recth = tpy;
661
662         /* for tiles, copy only part of image into buffer */
663         if (GTS.tilemode) {
664                 if (use_high_bit_depth) {
665                         float *frectrow, *ftilerectrow;
666
667                         ftilerect = MEM_mallocN(rectw*recth*sizeof(*ftilerect), "tilerect");
668
669                         for (y = 0; y < recth; y++) {
670                                 frectrow = &frect[y * ibuf->x];
671                                 ftilerectrow = &ftilerect[y * rectw];
672
673                                 memcpy(ftilerectrow, frectrow, tpx * sizeof(*frectrow));
674                         }
675
676                         frect = ftilerect;
677                 }
678                 else {
679                         unsigned int *rectrow, *tilerectrow;
680
681                         tilerect = MEM_mallocN(rectw*recth*sizeof(*tilerect), "tilerect");
682
683                         for (y = 0; y < recth; y++) {
684                                 rectrow = &rect[y * ibuf->x];
685                                 tilerectrow = &tilerect[y * rectw];
686
687                                 memcpy(tilerectrow, rectrow, tpx * sizeof(*rectrow));
688                         }
689                         
690                         rect = tilerect;
691                 }
692         }
693
694 #ifdef WITH_DDS
695         if (ibuf->ftype == IMB_FTYPE_DDS)
696                 GPU_create_gl_tex_compressed(bind, rect, rectw, recth, mipmap, ima, ibuf);
697         else
698 #endif
699                 GPU_create_gl_tex(bind, rect, frect, rectw, recth, mipmap, use_high_bit_depth, ima);
700         
701         /* mark as non-color data texture */
702         if (*bind) {
703                 if (is_data)
704                         ima->tpageflag |= IMA_GLBIND_IS_DATA;   
705                 else
706                         ima->tpageflag &= ~IMA_GLBIND_IS_DATA;  
707         }
708
709         /* clean up */
710         if (tilerect)
711                 MEM_freeN(tilerect);
712         if (ftilerect)
713                 MEM_freeN(ftilerect);
714         if (srgb_frect)
715                 MEM_freeN(srgb_frect);
716
717         BKE_image_release_ibuf(ima, ibuf, NULL);
718
719         return *bind;
720 }
721
722 /* Image *ima can be NULL */
723 void GPU_create_gl_tex(unsigned int *bind, unsigned int *rect, float *frect, int rectw, int recth,
724                        bool mipmap, bool use_high_bit_depth, Image *ima)
725 {
726         ImBuf *ibuf = NULL;
727
728         int tpx = rectw;
729         int tpy = recth;
730
731         /* scale if not a power of two. this is not strictly necessary for newer
732          * GPUs (OpenGL version >= 2.0) since they support non-power-of-two-textures 
733          * Then don't bother scaling for hardware that supports NPOT textures! */
734         if ((!GPU_non_power_of_two_support() && !is_power_of_2_resolution(rectw, recth)) ||
735                 is_over_resolution_limit(rectw, recth)) {
736                 rectw = smaller_power_of_2_limit(rectw);
737                 recth = smaller_power_of_2_limit(recth);
738                 
739                 if (use_high_bit_depth) {
740                         ibuf = IMB_allocFromBuffer(NULL, frect, tpx, tpy);
741                         IMB_scaleImBuf(ibuf, rectw, recth);
742
743                         frect = ibuf->rect_float;
744                 }
745                 else {
746                         ibuf = IMB_allocFromBuffer(rect, NULL, tpx, tpy);
747                         IMB_scaleImBuf(ibuf, rectw, recth);
748
749                         rect = ibuf->rect;
750                 }
751         }
752
753         /* create image */
754         glGenTextures(1, (GLuint *)bind);
755         glBindTexture(GL_TEXTURE_2D, *bind);
756
757         if (use_high_bit_depth) {
758                 if (GLEW_ARB_texture_float)
759                         glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA16F, rectw, recth, 0, GL_RGBA, GL_FLOAT, frect);
760                 else
761                         glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA16, rectw, recth, 0, GL_RGBA, GL_FLOAT, frect);
762         }
763         else
764                 glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, rectw, recth, 0, GL_RGBA, GL_UNSIGNED_BYTE, rect);
765
766         glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, gpu_get_mipmap_filter(1));
767
768         if (GPU_get_mipmap() && mipmap) {
769                 if (GTS.gpu_mipmap) {
770                         gpu_generate_mipmap(GL_TEXTURE_2D);
771                 }
772                 else {
773                         int i;
774
775                         if (!ibuf) {
776                                 if (use_high_bit_depth) {
777                                         ibuf = IMB_allocFromBuffer(NULL, frect, tpx, tpy);
778                                 }
779                                 else {
780                                         ibuf = IMB_allocFromBuffer(rect, NULL, tpx, tpy);
781                                 }
782                         }
783
784                         IMB_makemipmap(ibuf, true);
785
786                         for (i = 1; i < ibuf->miptot; i++) {
787                                 ImBuf *mip = ibuf->mipmap[i - 1];
788                                 if (use_high_bit_depth) {
789                                         if (GLEW_ARB_texture_float)
790                                                 glTexImage2D(GL_TEXTURE_2D, i, GL_RGBA16F, mip->x, mip->y, 0, GL_RGBA, GL_FLOAT, mip->rect_float);
791                                         else
792                                                 glTexImage2D(GL_TEXTURE_2D, i, GL_RGBA16, mip->x, mip->y, 0, GL_RGBA, GL_FLOAT, mip->rect_float);
793                                 }
794                                 else {
795                                         glTexImage2D(GL_TEXTURE_2D, i, GL_RGBA, mip->x, mip->y, 0, GL_RGBA, GL_UNSIGNED_BYTE, mip->rect);
796                                 }
797                         }
798                 }
799                 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, gpu_get_mipmap_filter(0));
800
801                 if (ima)
802                         ima->tpageflag |= IMA_MIPMAP_COMPLETE;
803         }
804         else {
805                 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
806         }
807
808         if (GLEW_EXT_texture_filter_anisotropic)
809                 glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAX_ANISOTROPY_EXT, GPU_get_anisotropic());
810         /* set to modulate with vertex color */
811         glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);
812
813         if (ibuf)
814                 IMB_freeImBuf(ibuf);
815 }
816
817 /**
818  * GPU_upload_dxt_texture() assumes that the texture is already bound and ready to go.
819  * This is so the viewport and the BGE can share some code.
820  * Returns false if the provided ImBuf doesn't have a supported DXT compression format
821  */
822 bool GPU_upload_dxt_texture(ImBuf *ibuf)
823 {
824 #ifdef WITH_DDS
825         GLint format = 0;
826         int blocksize, height, width, i, size, offset = 0;
827
828         width = ibuf->x;
829         height = ibuf->y;
830
831         if (GLEW_EXT_texture_compression_s3tc) {
832                 if (ibuf->dds_data.fourcc == FOURCC_DXT1)
833                         format = GL_COMPRESSED_RGBA_S3TC_DXT1_EXT;
834                 else if (ibuf->dds_data.fourcc == FOURCC_DXT3)
835                         format = GL_COMPRESSED_RGBA_S3TC_DXT3_EXT;
836                 else if (ibuf->dds_data.fourcc == FOURCC_DXT5)
837                         format = GL_COMPRESSED_RGBA_S3TC_DXT5_EXT;
838         }
839
840         if (format == 0) {
841                 fprintf(stderr, "Unable to find a suitable DXT compression, falling back to uncompressed\n");
842                 return false;
843         }
844
845         if (!is_power_of_2_resolution(width, height)) {
846                 fprintf(stderr, "Unable to load non-power-of-two DXT image resolution, falling back to uncompressed\n");
847                 return false;
848         }
849
850         glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, gpu_get_mipmap_filter(0));
851         glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, gpu_get_mipmap_filter(1));
852
853         glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);
854
855         if (GLEW_EXT_texture_filter_anisotropic)
856                 glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAX_ANISOTROPY_EXT, GPU_get_anisotropic());
857
858         blocksize = (ibuf->dds_data.fourcc == FOURCC_DXT1) ? 8 : 16;
859         for (i = 0; i < ibuf->dds_data.nummipmaps && (width||height); ++i) {
860                 if (width == 0)
861                         width = 1;
862                 if (height == 0)
863                         height = 1;
864
865                 size = ((width+3)/4)*((height+3)/4)*blocksize;
866
867                 glCompressedTexImage2D(GL_TEXTURE_2D, i, format, width, height,
868                         0, size, ibuf->dds_data.data + offset);
869
870                 offset += size;
871                 width >>= 1;
872                 height >>= 1;
873         }
874
875         /* set number of mipmap levels we have, needed in case they don't go down to 1x1 */
876         glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAX_LEVEL, i - 1);
877
878         return true;
879 #else
880         (void)ibuf;
881         return false;
882 #endif
883 }
884
885 void GPU_create_gl_tex_compressed(unsigned int *bind, unsigned int *pix, int x, int y, int mipmap, Image *ima, ImBuf *ibuf)
886 {
887 #ifndef WITH_DDS
888         (void)ibuf;
889         /* Fall back to uncompressed if DDS isn't enabled */
890         GPU_create_gl_tex(bind, pix, NULL, x, y, mipmap, 0, ima);
891 #else
892
893
894         glGenTextures(1, (GLuint *)bind);
895         glBindTexture(GL_TEXTURE_2D, *bind);
896
897         if (GPU_upload_dxt_texture(ibuf) == 0) {
898                 glDeleteTextures(1, (GLuint *)bind);
899                 GPU_create_gl_tex(bind, pix, NULL, x, y, mipmap, 0, ima);
900         }
901 #endif
902 }
903 static void gpu_verify_repeat(Image *ima)
904 {
905         /* set either clamp or repeat in X/Y */
906         if (ima->tpageflag & IMA_CLAMP_U)
907                 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
908         else
909                 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
910
911         if (ima->tpageflag & IMA_CLAMP_V)
912                 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
913         else
914                 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
915 }
916
917 int GPU_set_tpage(MTexPoly *mtexpoly, int mipmap, int alphablend)
918 {
919         Image *ima;
920         
921         /* check if we need to clear the state */
922         if (mtexpoly == NULL) {
923                 GPU_clear_tpage(false);
924                 return 0;
925         }
926
927         ima = mtexpoly->tpage;
928         GTS.lasttface = mtexpoly;
929
930         gpu_verify_alpha_blend(alphablend);
931         gpu_verify_reflection(ima);
932
933         if (GPU_verify_image(ima, NULL, mtexpoly->tile, 1, mipmap, false)) {
934                 GTS.curtile = GTS.tile;
935                 GTS.curima = GTS.ima;
936                 GTS.curtilemode = GTS.tilemode;
937                 GTS.curtileXRep = GTS.tileXRep;
938                 GTS.curtileYRep = GTS.tileYRep;
939
940                 glEnable(GL_TEXTURE_2D);
941         }
942         else {
943                 glDisable(GL_TEXTURE_2D);
944                 
945                 GTS.curtile = 0;
946                 GTS.curima = NULL;
947                 GTS.curtilemode = 0;
948                 GTS.curtileXRep = 0;
949                 GTS.curtileYRep = 0;
950
951                 return 0;
952         }
953         
954         gpu_verify_repeat(ima);
955         
956         /* Did this get lost in the image recode? */
957         /* BKE_image_tag_time(ima);*/
958
959         return 1;
960 }
961
962 /* these two functions are called on entering and exiting texture paint mode,
963  * temporary disabling/enabling mipmapping on all images for quick texture
964  * updates with glTexSubImage2D. images that didn't change don't have to be
965  * re-uploaded to OpenGL */
966 void GPU_paint_set_mipmap(bool mipmap)
967 {
968         Image *ima;
969         
970         if (!GTS.domipmap)
971                 return;
972
973         GTS.texpaint = !mipmap;
974
975         if (mipmap) {
976                 for (ima = G.main->image.first; ima; ima = ima->id.next) {
977                         if (ima->bindcode) {
978                                 if (ima->tpageflag & IMA_MIPMAP_COMPLETE) {
979                                         glBindTexture(GL_TEXTURE_2D, ima->bindcode);
980                                         glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, gpu_get_mipmap_filter(0));
981                                         glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, gpu_get_mipmap_filter(1));
982                                 }
983                                 else
984                                         GPU_free_image(ima);
985                         }
986                         else
987                                 ima->tpageflag &= ~IMA_MIPMAP_COMPLETE;
988                 }
989
990         }
991         else {
992                 for (ima = G.main->image.first; ima; ima = ima->id.next) {
993                         if (ima->bindcode) {
994                                 glBindTexture(GL_TEXTURE_2D, ima->bindcode);
995                                 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
996                                 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, gpu_get_mipmap_filter(1));
997                         }
998                         else
999                                 ima->tpageflag &= ~IMA_MIPMAP_COMPLETE;
1000                 }
1001         }
1002 }
1003
1004
1005 /* check if image has been downscaled and do scaled partial update */
1006 static bool GPU_check_scaled_image(ImBuf *ibuf, Image *ima, float *frect, int x, int y, int w, int h)
1007 {
1008         if ((!GPU_non_power_of_two_support() && !is_power_of_2_resolution(ibuf->x, ibuf->y)) ||
1009             is_over_resolution_limit(ibuf->x, ibuf->y))
1010         {
1011                 int x_limit = smaller_power_of_2_limit(ibuf->x);
1012                 int y_limit = smaller_power_of_2_limit(ibuf->y);
1013
1014                 float xratio = x_limit / (float)ibuf->x;
1015                 float yratio = y_limit / (float)ibuf->y;
1016
1017                 /* find new width, height and x,y gpu texture coordinates */
1018
1019                 /* take ceiling because we will be losing 1 pixel due to rounding errors in x,y... */
1020                 int rectw = (int)ceil(xratio * w);
1021                 int recth = (int)ceil(yratio * h);
1022
1023                 x *= xratio;
1024                 y *= yratio;
1025
1026                 /* ...but take back if we are over the limit! */
1027                 if (rectw + x > x_limit) rectw--;
1028                 if (recth + y > y_limit) recth--;
1029
1030                 /* float rectangles are already continuous in memory so we can use IMB_scaleImBuf */
1031                 if (frect) {
1032                         ImBuf *ibuf = IMB_allocFromBuffer(NULL, frect, w, h);
1033                         IMB_scaleImBuf(ibuf, rectw, recth);
1034
1035                         glBindTexture(GL_TEXTURE_2D, ima->bindcode);
1036                         glTexSubImage2D(GL_TEXTURE_2D, 0, x, y, rectw, recth, GL_RGBA,
1037                                         GL_FLOAT, ibuf->rect_float);
1038
1039                         IMB_freeImBuf(ibuf);
1040                 }
1041                 /* byte images are not continuous in memory so do manual interpolation */
1042                 else {
1043                         unsigned char *scalerect = MEM_mallocN(rectw * recth * sizeof(*scalerect) * 4, "scalerect");
1044                         unsigned int *p = (unsigned int *)scalerect;
1045                         int i, j;
1046                         float inv_xratio = 1.0f / xratio;
1047                         float inv_yratio = 1.0f / yratio;
1048                         for (i = 0; i < rectw; i++) {
1049                                 float u = (x + i) * inv_xratio;
1050                                 for (j = 0; j < recth; j++) {
1051                                         float v = (y + j) * inv_yratio;
1052                                         bilinear_interpolation_color_wrap(ibuf, (unsigned char *)(p + i + j * (rectw)), NULL, u, v);
1053                                 }
1054                         }
1055                         glBindTexture(GL_TEXTURE_2D, ima->bindcode);
1056                         glTexSubImage2D(GL_TEXTURE_2D, 0, x, y, rectw, recth, GL_RGBA,
1057                                         GL_UNSIGNED_BYTE, scalerect);
1058
1059                         MEM_freeN(scalerect);
1060                 }
1061
1062                 if (GPU_get_mipmap()) {
1063                         gpu_generate_mipmap(GL_TEXTURE_2D);
1064                 }
1065                 else {
1066                         ima->tpageflag &= ~IMA_MIPMAP_COMPLETE;
1067                 }
1068
1069                 return true;
1070         }
1071
1072         return false;
1073 }
1074
1075 void GPU_paint_update_image(Image *ima, ImageUser *iuser, int x, int y, int w, int h)
1076 {
1077         ImBuf *ibuf;
1078         
1079         ibuf = BKE_image_acquire_ibuf(ima, iuser, NULL);
1080         
1081         if (ima->repbind || (GPU_get_mipmap() && !GTS.gpu_mipmap) || !ima->bindcode || !ibuf ||
1082                 (w == 0) || (h == 0))
1083         {
1084                 /* these cases require full reload still */
1085                 GPU_free_image(ima);
1086         }
1087         else {
1088                 /* for the special case, we can do a partial update
1089                  * which is much quicker for painting */
1090                 GLint row_length, skip_pixels, skip_rows;
1091
1092                 /* if color correction is needed, we must update the part that needs updating. */
1093                 if (ibuf->rect_float) {
1094                         float *buffer = MEM_mallocN(w * h * sizeof(float) * 4, "temp_texpaint_float_buf");
1095                         bool is_data = (ima->tpageflag & IMA_GLBIND_IS_DATA) != 0;
1096                         IMB_partial_rect_from_float(ibuf, buffer, x, y, w, h, is_data);
1097                         
1098                         if (GPU_check_scaled_image(ibuf, ima, buffer, x, y, w, h)) {
1099                                 MEM_freeN(buffer);
1100                                 BKE_image_release_ibuf(ima, ibuf, NULL);
1101                                 return;
1102                         }
1103
1104                         glBindTexture(GL_TEXTURE_2D, ima->bindcode);
1105                         glTexSubImage2D(GL_TEXTURE_2D, 0, x, y, w, h, GL_RGBA, GL_FLOAT, buffer);
1106
1107                         MEM_freeN(buffer);
1108
1109                         /* we have already accounted for the case where GTS.gpu_mipmap is false
1110                          * so we will be using GPU mipmap generation here */
1111                         if (GPU_get_mipmap()) {
1112                                 gpu_generate_mipmap(GL_TEXTURE_2D);
1113                         }
1114                         else {
1115                                 ima->tpageflag &= ~IMA_MIPMAP_COMPLETE;
1116                         }
1117
1118                         BKE_image_release_ibuf(ima, ibuf, NULL);
1119                         return;
1120                 }
1121
1122                 if (GPU_check_scaled_image(ibuf, ima, NULL, x, y, w, h)) {
1123                         BKE_image_release_ibuf(ima, ibuf, NULL);
1124                         return;
1125                 }
1126
1127                 glBindTexture(GL_TEXTURE_2D, ima->bindcode);
1128
1129                 glGetIntegerv(GL_UNPACK_ROW_LENGTH, &row_length);
1130                 glGetIntegerv(GL_UNPACK_SKIP_PIXELS, &skip_pixels);
1131                 glGetIntegerv(GL_UNPACK_SKIP_ROWS, &skip_rows);
1132
1133                 glPixelStorei(GL_UNPACK_ROW_LENGTH, ibuf->x);
1134                 glPixelStorei(GL_UNPACK_SKIP_PIXELS, x);
1135                 glPixelStorei(GL_UNPACK_SKIP_ROWS, y);
1136
1137                 glTexSubImage2D(GL_TEXTURE_2D, 0, x, y, w, h, GL_RGBA,
1138                         GL_UNSIGNED_BYTE, ibuf->rect);
1139
1140                 glPixelStorei(GL_UNPACK_ROW_LENGTH, row_length);
1141                 glPixelStorei(GL_UNPACK_SKIP_PIXELS, skip_pixels);
1142                 glPixelStorei(GL_UNPACK_SKIP_ROWS, skip_rows);
1143
1144                 /* see comment above as to why we are using gpu mipmap generation here */
1145                 if (GPU_get_mipmap()) {
1146                         gpu_generate_mipmap(GL_TEXTURE_2D);
1147                 }
1148                 else {
1149                         ima->tpageflag &= ~IMA_MIPMAP_COMPLETE;
1150                 }
1151         }
1152
1153         BKE_image_release_ibuf(ima, ibuf, NULL);
1154 }
1155
1156 void GPU_update_images_framechange(void)
1157 {
1158         Image *ima;
1159         
1160         for (ima = G.main->image.first; ima; ima = ima->id.next) {
1161                 if (ima->tpageflag & IMA_TWINANIM) {
1162                         if (ima->twend >= ima->xrep * ima->yrep)
1163                                 ima->twend = ima->xrep * ima->yrep - 1;
1164                 
1165                         /* check: is bindcode not in the array? free. (to do) */
1166                         
1167                         ima->lastframe++;
1168                         if (ima->lastframe > ima->twend)
1169                                 ima->lastframe = ima->twsta;
1170                 }
1171         }
1172 }
1173
1174 int GPU_update_image_time(Image *ima, double time)
1175 {
1176         int     inc = 0;
1177         float diff;
1178         int     newframe;
1179
1180         if (!ima)
1181                 return 0;
1182
1183         if (ima->lastupdate < 0)
1184                 ima->lastupdate = 0;
1185
1186         if (ima->lastupdate > (float)time)
1187                 ima->lastupdate = (float)time;
1188
1189         if (ima->tpageflag & IMA_TWINANIM) {
1190                 if (ima->twend >= ima->xrep * ima->yrep) ima->twend = ima->xrep * ima->yrep - 1;
1191                 
1192                 /* check: is the bindcode not in the array? Then free. (still to do) */
1193                 
1194                 diff = (float)((float)time - ima->lastupdate);
1195                 inc = (int)(diff * (float)ima->animspeed);
1196
1197                 ima->lastupdate += ((float)inc / (float)ima->animspeed);
1198
1199                 newframe = ima->lastframe + inc;
1200
1201                 if (newframe > (int)ima->twend) {
1202                         if (ima->twend - ima->twsta != 0)
1203                                 newframe = (int)ima->twsta - 1 + (newframe - ima->twend) % (ima->twend - ima->twsta);
1204                         else
1205                                 newframe = ima->twsta;
1206                 }
1207
1208                 ima->lastframe = newframe;
1209         }
1210
1211         return inc;
1212 }
1213
1214
1215 void GPU_free_smoke(SmokeModifierData *smd)
1216 {
1217         if (smd->type & MOD_SMOKE_TYPE_DOMAIN && smd->domain) {
1218                 if (smd->domain->tex)
1219                         GPU_texture_free(smd->domain->tex);
1220                 smd->domain->tex = NULL;
1221
1222                 if (smd->domain->tex_shadow)
1223                         GPU_texture_free(smd->domain->tex_shadow);
1224                 smd->domain->tex_shadow = NULL;
1225
1226                 if (smd->domain->tex_flame)
1227                         GPU_texture_free(smd->domain->tex_flame);
1228                 smd->domain->tex_flame = NULL;
1229         }
1230 }
1231
1232 void GPU_create_smoke(SmokeModifierData *smd, int highres)
1233 {
1234 #ifdef WITH_SMOKE
1235         if (smd->type & MOD_SMOKE_TYPE_DOMAIN) {
1236                 SmokeDomainSettings *sds = smd->domain;
1237                 if (!sds->tex && !highres) {
1238                         /* rgba texture for color + density */
1239                         if (smoke_has_colors(sds->fluid)) {
1240                                 float *data = MEM_callocN(sizeof(float) * sds->total_cells * 4, "smokeColorTexture");
1241                                 smoke_get_rgba(sds->fluid, data, 0);
1242                                 sds->tex = GPU_texture_create_3D(sds->res[0], sds->res[1], sds->res[2], 4, data);
1243                                 MEM_freeN(data);
1244                         }
1245                         /* density only */
1246                         else {
1247                                 sds->tex = GPU_texture_create_3D(sds->res[0], sds->res[1], sds->res[2], 1, smoke_get_density(sds->fluid));
1248                         }
1249                         sds->tex_flame = (smoke_has_fuel(sds->fluid)) ? GPU_texture_create_3D(sds->res[0], sds->res[1], sds->res[2], 1, smoke_get_flame(sds->fluid)) : NULL;
1250                 }
1251                 else if (!sds->tex && highres) {
1252                         /* rgba texture for color + density */
1253                         if (smoke_turbulence_has_colors(sds->wt)) {
1254                                 float *data = MEM_callocN(sizeof(float) * smoke_turbulence_get_cells(sds->wt) * 4, "smokeColorTexture");
1255                                 smoke_turbulence_get_rgba(sds->wt, data, 0);
1256                                 sds->tex = GPU_texture_create_3D(sds->res_wt[0], sds->res_wt[1], sds->res_wt[2], 4, data);
1257                                 MEM_freeN(data);
1258                         }
1259                         /* density only */
1260                         else {
1261                                 sds->tex = GPU_texture_create_3D(sds->res_wt[0], sds->res_wt[1], sds->res_wt[2], 1, smoke_turbulence_get_density(sds->wt));
1262                         }
1263                         sds->tex_flame = (smoke_turbulence_has_fuel(sds->wt)) ? GPU_texture_create_3D(sds->res_wt[0], sds->res_wt[1], sds->res_wt[2], 1, smoke_turbulence_get_flame(sds->wt)) : NULL;
1264                 }
1265
1266                 sds->tex_shadow = GPU_texture_create_3D(sds->res[0], sds->res[1], sds->res[2], 1, sds->shadow);
1267         }
1268 #else // WITH_SMOKE
1269         (void)highres;
1270         smd->domain->tex = NULL;
1271         smd->domain->tex_flame = NULL;
1272         smd->domain->tex_shadow = NULL;
1273 #endif // WITH_SMOKE
1274 }
1275
1276 static LinkNode *image_free_queue = NULL;
1277
1278 static void gpu_queue_image_for_free(Image *ima)
1279 {
1280         BLI_lock_thread(LOCK_OPENGL);
1281         BLI_linklist_prepend(&image_free_queue, ima);
1282         BLI_unlock_thread(LOCK_OPENGL);
1283 }
1284
1285 void GPU_free_unused_buffers(void)
1286 {
1287         LinkNode *node;
1288         Image *ima;
1289
1290         if (!BLI_thread_is_main())
1291                 return;
1292
1293         BLI_lock_thread(LOCK_OPENGL);
1294
1295         /* images */
1296         for (node = image_free_queue; node; node = node->next) {
1297                 ima = node->link;
1298
1299                 /* check in case it was freed in the meantime */
1300                 if (G.main && BLI_findindex(&G.main->image, ima) != -1)
1301                         GPU_free_image(ima);
1302         }
1303
1304         BLI_linklist_free(image_free_queue, NULL);
1305         image_free_queue = NULL;
1306
1307         /* vbo buffers */
1308         GPU_global_buffer_pool_free_unused();
1309
1310         BLI_unlock_thread(LOCK_OPENGL);
1311 }
1312
1313 void GPU_free_image(Image *ima)
1314 {
1315         if (!BLI_thread_is_main()) {
1316                 gpu_queue_image_for_free(ima);
1317                 return;
1318         }
1319
1320         /* free regular image binding */
1321         if (ima->bindcode) {
1322                 glDeleteTextures(1, (GLuint *)&ima->bindcode);
1323                 ima->bindcode = 0;
1324         }
1325
1326         /* free glsl image binding */
1327         if (ima->gputexture) {
1328                 GPU_texture_free(ima->gputexture);
1329                 ima->gputexture = NULL;
1330         }
1331
1332         /* free repeated image binding */
1333         if (ima->repbind) {
1334                 glDeleteTextures(ima->totbind, (GLuint *)ima->repbind);
1335         
1336                 MEM_freeN(ima->repbind);
1337                 ima->repbind = NULL;
1338         }
1339
1340         ima->tpageflag &= ~(IMA_MIPMAP_COMPLETE|IMA_GLBIND_IS_DATA);
1341 }
1342
1343 void GPU_free_images(void)
1344 {
1345         Image *ima;
1346
1347         if (G.main)
1348                 for (ima = G.main->image.first; ima; ima = ima->id.next)
1349                         GPU_free_image(ima);
1350 }
1351
1352 /* same as above but only free animated images */
1353 void GPU_free_images_anim(void)
1354 {
1355         Image *ima;
1356
1357         if (G.main)
1358                 for (ima = G.main->image.first; ima; ima = ima->id.next)
1359                         if (BKE_image_is_animated(ima))
1360                                 GPU_free_image(ima);
1361 }
1362
1363
1364 void GPU_free_images_old(void)
1365 {
1366         Image *ima;
1367         static int lasttime = 0;
1368         int ctime = (int)PIL_check_seconds_timer();
1369
1370         /*
1371          * Run garbage collector once for every collecting period of time
1372          * if textimeout is 0, that's the option to NOT run the collector
1373          */
1374         if (U.textimeout == 0 || ctime % U.texcollectrate || ctime == lasttime)
1375                 return;
1376
1377         /* of course not! */
1378         if (G.is_rendering)
1379                 return;
1380
1381         lasttime = ctime;
1382
1383         ima = G.main->image.first;
1384         while (ima) {
1385                 if ((ima->flag & IMA_NOCOLLECT) == 0 && ctime - ima->lastused > U.textimeout) {
1386                         /* If it's in GL memory, deallocate and set time tag to current time
1387                          * This gives textures a "second chance" to be used before dying. */
1388                         if (ima->bindcode || ima->repbind) {
1389                                 GPU_free_image(ima);
1390                                 ima->lastused = ctime;
1391                         }
1392                         /* Otherwise, just kill the buffers */
1393                         else {
1394                                 BKE_image_free_buffers(ima);
1395                         }
1396                 }
1397                 ima = ima->id.next;
1398         }
1399 }
1400
1401
1402 /* OpenGL Materials */
1403
1404 #define FIXEDMAT 8
1405
1406 /* OpenGL state caching for materials */
1407
1408 typedef struct GPUMaterialFixed {
1409         float diff[4];
1410         float spec[4];
1411         int hard;
1412 } GPUMaterialFixed; 
1413
1414 static struct GPUMaterialState {
1415         GPUMaterialFixed (*matbuf);
1416         GPUMaterialFixed matbuf_fixed[FIXEDMAT];
1417         int totmat;
1418
1419         /* set when called inside GPU_begin_object_materials / GPU_end_object_materials
1420          * otherwise calling GPU_enable_material returns zero */
1421         bool is_enabled;
1422
1423         Material **gmatbuf;
1424         Material *gmatbuf_fixed[FIXEDMAT];
1425         Material *gboundmat;
1426         Object *gob;
1427         DupliObject *dob;
1428         Scene *gscene;
1429         int glay;
1430         bool gscenelock;
1431         float (*gviewmat)[4];
1432         float (*gviewinv)[4];
1433         float (*gviewcamtexcofac);
1434
1435         bool backface_culling;
1436
1437         GPUBlendMode *alphablend;
1438         GPUBlendMode alphablend_fixed[FIXEDMAT];
1439         bool use_alpha_pass, is_alpha_pass;
1440         bool use_matcaps;
1441
1442         int lastmatnr, lastretval;
1443         GPUBlendMode lastalphablend;
1444         bool is_opensubdiv;
1445 } GMS = {NULL};
1446
1447 /* fixed function material, alpha handed by caller */
1448 static void gpu_material_to_fixed(GPUMaterialFixed *smat, const Material *bmat, const int gamma, const Object *ob, const int new_shading_nodes, 
1449                                   const bool dimdown)
1450 {
1451         if (bmat->mode & MA_SHLESS) {
1452                 copy_v3_v3(smat->diff, &bmat->r);
1453                 smat->diff[3] = 1.0;
1454
1455                 if (gamma)
1456                         linearrgb_to_srgb_v3_v3(smat->diff, smat->diff);
1457
1458                 zero_v4(smat->spec);
1459                 smat->hard = 0;
1460         }
1461         else if (new_shading_nodes) {
1462                 copy_v3_v3(smat->diff, &bmat->r);
1463                 smat->diff[3] = 1.0;
1464                 
1465                 copy_v3_v3(smat->spec, &bmat->specr);
1466                 smat->spec[3] = 1.0;
1467                 smat->hard = CLAMPIS(bmat->har, 0, 128);
1468                 
1469                 if (dimdown) {
1470                         mul_v3_fl(smat->diff, 0.8f);
1471                         mul_v3_fl(smat->spec, 0.5f);
1472                 }
1473                 
1474                 if (gamma) {
1475                         linearrgb_to_srgb_v3_v3(smat->diff, smat->diff);
1476                         linearrgb_to_srgb_v3_v3(smat->spec, smat->spec);
1477                 }
1478         }
1479         else {
1480                 mul_v3_v3fl(smat->diff, &bmat->r, bmat->ref + bmat->emit);
1481                 smat->diff[3] = 1.0; /* caller may set this to bmat->alpha */
1482
1483                 if (bmat->shade_flag & MA_OBCOLOR)
1484                         mul_v3_v3(smat->diff, ob->col);
1485                 
1486                 mul_v3_v3fl(smat->spec, &bmat->specr, bmat->spec);
1487                 smat->spec[3] = 1.0; /* always 1 */
1488                 smat->hard= CLAMPIS(bmat->har, 0, 128);
1489
1490                 if (gamma) {
1491                         linearrgb_to_srgb_v3_v3(smat->diff, smat->diff);
1492                         linearrgb_to_srgb_v3_v3(smat->spec, smat->spec);
1493                 }
1494         }
1495 }
1496
1497 static Material *gpu_active_node_material(Material *ma)
1498 {
1499         if (ma && ma->use_nodes && ma->nodetree) {
1500                 bNode *node = nodeGetActiveID(ma->nodetree, ID_MA);
1501
1502                 if (node)
1503                         return (Material *)node->id;
1504                 else
1505                         return NULL;
1506         }
1507
1508         return ma;
1509 }
1510
1511 void GPU_begin_dupli_object(DupliObject *dob)
1512 {
1513         GMS.dob = dob;
1514 }
1515
1516 void GPU_end_dupli_object(void)
1517 {
1518         GMS.dob = NULL;
1519 }
1520
1521 void GPU_begin_object_materials(View3D *v3d, RegionView3D *rv3d, Scene *scene, Object *ob, bool glsl, bool *do_alpha_after)
1522 {
1523         Material *ma;
1524         GPUMaterial *gpumat;
1525         GPUBlendMode alphablend;
1526         DupliObject *dob;
1527         int a;
1528         const bool gamma = BKE_scene_check_color_management_enabled(scene);
1529         const bool new_shading_nodes = BKE_scene_use_new_shading_nodes(scene);
1530         const bool use_matcap = (v3d->flag2 & V3D_SHOW_SOLID_MATCAP) != 0;  /* assumes v3d->defmaterial->preview is set */
1531         bool use_opensubdiv = false;
1532
1533 #ifdef WITH_OPENSUBDIV
1534         {
1535                 DerivedMesh *derivedFinal = NULL;
1536                 Mesh *me = ob->data;
1537                 BMEditMesh *em = me->edit_btmesh;
1538
1539                 if (em != NULL) {
1540                         derivedFinal = em->derivedFinal;
1541                 }
1542                 else {
1543                         derivedFinal = ob->derivedFinal;
1544                 }
1545
1546                 if (derivedFinal != NULL && derivedFinal->type == DM_TYPE_CCGDM) {
1547                         CCGDerivedMesh *ccgdm = (CCGDerivedMesh *) derivedFinal;
1548                         use_opensubdiv = ccgdm->useGpuBackend;
1549                 }
1550         }
1551 #endif
1552
1553 #ifdef WITH_GAMEENGINE
1554         if (rv3d->rflag & RV3D_IS_GAME_ENGINE) {
1555                 ob = BKE_object_lod_matob_get(ob, scene);
1556         }
1557 #endif
1558
1559         /* initialize state */
1560         /* DupliObject must be restored */
1561         dob = GMS.dob;
1562         memset(&GMS, 0, sizeof(GMS));
1563         GMS.is_enabled = true;
1564         GMS.dob = dob;
1565         GMS.lastmatnr = -1;
1566         GMS.lastretval = -1;
1567         GMS.lastalphablend = GPU_BLEND_SOLID;
1568         GMS.use_matcaps = use_matcap;
1569
1570         GMS.backface_culling = (v3d->flag2 & V3D_BACKFACE_CULLING) != 0;
1571
1572         GMS.gob = ob;
1573         GMS.gscene = scene;
1574         GMS.is_opensubdiv = use_opensubdiv;
1575         GMS.totmat = use_matcap ? 1 : ob->totcol + 1;  /* materials start from 1, default material is 0 */
1576         GMS.glay = (v3d->localvd)? v3d->localvd->lay: v3d->lay; /* keep lamps visible in local view */
1577         GMS.gscenelock = (v3d->scenelock != 0);
1578         GMS.gviewmat = rv3d->viewmat;
1579         GMS.gviewinv = rv3d->viewinv;
1580         GMS.gviewcamtexcofac = rv3d->viewcamtexcofac;
1581
1582         /* alpha pass setup. there's various cases to handle here:
1583          * - object transparency on: only solid materials draw in the first pass,
1584          * and only transparent in the second 'alpha' pass.
1585          * - object transparency off: for glsl we draw both in a single pass, and
1586          * for solid we don't use transparency at all. */
1587         GMS.use_alpha_pass = (do_alpha_after != NULL);
1588         GMS.is_alpha_pass = (v3d->transp != false);
1589         if (GMS.use_alpha_pass)
1590                 *do_alpha_after = false;
1591         
1592         if (GMS.totmat > FIXEDMAT) {
1593                 GMS.matbuf = MEM_callocN(sizeof(GPUMaterialFixed) * GMS.totmat, "GMS.matbuf");
1594                 GMS.gmatbuf = MEM_callocN(sizeof(*GMS.gmatbuf) * GMS.totmat, "GMS.matbuf");
1595                 GMS.alphablend = MEM_callocN(sizeof(*GMS.alphablend) * GMS.totmat, "GMS.matbuf");
1596         }
1597         else {
1598                 GMS.matbuf = GMS.matbuf_fixed;
1599                 GMS.gmatbuf = GMS.gmatbuf_fixed;
1600                 GMS.alphablend = GMS.alphablend_fixed;
1601         }
1602
1603         /* viewport material, setup in space_view3d, defaults to matcap using ma->preview now */
1604         if (use_matcap) {
1605                 GMS.gmatbuf[0] = v3d->defmaterial;
1606                 GPU_material_matcap(scene, v3d->defmaterial, use_opensubdiv);
1607
1608                 /* do material 1 too, for displists! */
1609                 memcpy(&GMS.matbuf[1], &GMS.matbuf[0], sizeof(GPUMaterialFixed));
1610         
1611                 GMS.alphablend[0] = GPU_BLEND_SOLID;
1612         }
1613         else {
1614         
1615                 /* no materials assigned? */
1616                 if (ob->totcol == 0) {
1617                         gpu_material_to_fixed(&GMS.matbuf[0], &defmaterial, 0, ob, new_shading_nodes, true);
1618
1619                         /* do material 1 too, for displists! */
1620                         memcpy(&GMS.matbuf[1], &GMS.matbuf[0], sizeof(GPUMaterialFixed));
1621
1622                         if (glsl) {
1623                                 GMS.gmatbuf[0] = &defmaterial;
1624                                 GPU_material_from_blender(GMS.gscene, &defmaterial, GMS.is_opensubdiv);
1625                         }
1626
1627                         GMS.alphablend[0] = GPU_BLEND_SOLID;
1628                 }
1629                 
1630                 /* setup materials */
1631                 for (a = 1; a <= ob->totcol; a++) {
1632                         /* find a suitable material */
1633                         ma = give_current_material(ob, a);
1634                         if (!glsl && !new_shading_nodes) ma = gpu_active_node_material(ma);
1635                         if (ma == NULL) ma = &defmaterial;
1636
1637                         /* create glsl material if requested */
1638                         gpumat = glsl? GPU_material_from_blender(GMS.gscene, ma, GMS.is_opensubdiv): NULL;
1639
1640                         if (gpumat) {
1641                                 /* do glsl only if creating it succeed, else fallback */
1642                                 GMS.gmatbuf[a] = ma;
1643                                 alphablend = GPU_material_alpha_blend(gpumat, ob->col);
1644                         }
1645                         else {
1646                                 /* fixed function opengl materials */
1647                                 gpu_material_to_fixed(&GMS.matbuf[a], ma, gamma, ob, new_shading_nodes, false);
1648
1649                                 if (GMS.use_alpha_pass && ((ma->mode & MA_TRANSP) || (new_shading_nodes && ma->alpha != 1.0f))) {
1650                                         GMS.matbuf[a].diff[3] = ma->alpha;
1651                                         alphablend = (ma->alpha == 1.0f)? GPU_BLEND_SOLID: GPU_BLEND_ALPHA;
1652                                 }
1653                                 else {
1654                                         GMS.matbuf[a].diff[3] = 1.0f;
1655                                         alphablend = GPU_BLEND_SOLID;
1656                                 }
1657                         }
1658
1659                         /* setting 'do_alpha_after = true' indicates this object needs to be
1660                          * drawn in a second alpha pass for improved blending */
1661                         if (do_alpha_after && !GMS.is_alpha_pass)
1662                                 if (ELEM(alphablend, GPU_BLEND_ALPHA, GPU_BLEND_ADD, GPU_BLEND_ALPHA_SORT))
1663                                         *do_alpha_after = true;
1664
1665                         GMS.alphablend[a] = alphablend;
1666                 }
1667         }
1668
1669         /* let's start with a clean state */
1670         GPU_disable_material();
1671 }
1672
1673 static int GPU_get_particle_info(GPUParticleInfo *pi)
1674 {
1675         ParticleData *p;
1676         DupliObject *dob = GMS.dob;
1677         int ind;
1678         if (dob->particle_system) {
1679                 if (dob->persistent_id[0] < dob->particle_system->totpart)
1680                         ind = dob->persistent_id[0];
1681                 else {
1682                         ind = dob->particle_system->child[dob->persistent_id[0] - dob->particle_system->totpart].parent;
1683                 }
1684                 if (ind >= 0) {
1685                         p = &dob->particle_system->particles[ind];
1686
1687                         pi->scalprops[0] = ind;
1688                         pi->scalprops[1] = GMS.gscene->r.cfra - p->time;
1689                         pi->scalprops[2] = p->lifetime;
1690                         pi->scalprops[3] = p->size;
1691
1692                         copy_v3_v3(pi->location, p->state.co);
1693                         copy_v3_v3(pi->velocity, p->state.vel);
1694                         copy_v3_v3(pi->angular_velocity, p->state.ave);
1695                         return 1;
1696                 }
1697                 else return 0;
1698         }
1699         else
1700                 return 0;
1701 }
1702
1703 int GPU_enable_material(int nr, void *attribs)
1704 {
1705         GPUVertexAttribs *gattribs = attribs;
1706         GPUMaterial *gpumat;
1707         GPUBlendMode alphablend;
1708
1709         /* no GPU_begin_object_materials, use default material */
1710         if (!GMS.matbuf) {
1711                 float diff[4], spec[4];
1712
1713                 memset(&GMS, 0, sizeof(GMS));
1714
1715                 mul_v3_v3fl(diff, &defmaterial.r, defmaterial.ref + defmaterial.emit);
1716                 diff[3] = 1.0;
1717
1718                 mul_v3_v3fl(spec, &defmaterial.specr, defmaterial.spec);
1719                 spec[3] = 1.0;
1720
1721                 glMaterialfv(GL_FRONT_AND_BACK, GL_DIFFUSE, diff);
1722                 glMaterialfv(GL_FRONT_AND_BACK, GL_SPECULAR, spec);
1723                 glMateriali(GL_FRONT_AND_BACK, GL_SHININESS, 35); /* blender default */
1724
1725                 return 0;
1726         }
1727
1728         /* prevent index to use un-initialized array items */
1729         if (nr >= GMS.totmat)
1730                 nr = 0;
1731
1732         if (gattribs)
1733                 memset(gattribs, 0, sizeof(*gattribs));
1734
1735         /* keep current material */
1736         if (nr == GMS.lastmatnr)
1737                 return GMS.lastretval;
1738
1739         /* unbind glsl material */
1740         if (GMS.gboundmat) {
1741                 if (GMS.is_alpha_pass) glDepthMask(0);
1742                 GPU_material_unbind(GPU_material_from_blender(GMS.gscene, GMS.gboundmat, GMS.is_opensubdiv));
1743                 GMS.gboundmat = NULL;
1744         }
1745
1746         /* draw materials with alpha in alpha pass */
1747         GMS.lastmatnr = nr;
1748         GMS.lastretval = 1;
1749
1750         if (GMS.use_alpha_pass) {
1751                 GMS.lastretval = ELEM(GMS.alphablend[nr], GPU_BLEND_SOLID, GPU_BLEND_CLIP);
1752                 if (GMS.is_alpha_pass)
1753                         GMS.lastretval = !GMS.lastretval;
1754         }
1755         else
1756                 GMS.lastretval = !GMS.is_alpha_pass;
1757
1758         if (GMS.lastretval) {
1759                 /* for alpha pass, use alpha blend */
1760                 alphablend = GMS.alphablend[nr];
1761
1762                 if (gattribs && GMS.gmatbuf[nr]) {
1763                         /* bind glsl material and get attributes */
1764                         Material *mat = GMS.gmatbuf[nr];
1765                         GPUParticleInfo partile_info;
1766
1767                         float auto_bump_scale;
1768
1769                         gpumat = GPU_material_from_blender(GMS.gscene, mat, GMS.is_opensubdiv);
1770                         GPU_material_vertex_attributes(gpumat, gattribs);
1771
1772                         if (GMS.dob)
1773                                 GPU_get_particle_info(&partile_info);
1774
1775                         GPU_material_bind(gpumat, GMS.gob->lay, GMS.glay, 1.0, !(GMS.gob->mode & OB_MODE_TEXTURE_PAINT), GMS.gviewmat, GMS.gviewinv, GMS.gviewcamtexcofac, GMS.gscenelock);
1776
1777                         auto_bump_scale = GMS.gob->derivedFinal != NULL ? GMS.gob->derivedFinal->auto_bump_scale : 1.0f;
1778                         GPU_material_bind_uniforms(gpumat, GMS.gob->obmat, GMS.gob->col, auto_bump_scale, &partile_info);
1779                         GMS.gboundmat = mat;
1780
1781                         /* for glsl use alpha blend mode, unless it's set to solid and
1782                          * we are already drawing in an alpha pass */
1783                         if (mat->game.alpha_blend != GPU_BLEND_SOLID)
1784                                 alphablend= mat->game.alpha_blend;
1785
1786                         if (GMS.is_alpha_pass) glDepthMask(1);
1787
1788                         if (GMS.backface_culling) {
1789                                 if (mat->game.flag)
1790                                         glEnable(GL_CULL_FACE);
1791                                 else
1792                                         glDisable(GL_CULL_FACE);
1793                         }
1794
1795                         if (GMS.use_matcaps)
1796                                 glColor3f(1.0f, 1.0f, 1.0f);
1797                 }
1798                 else {
1799                         /* or do fixed function opengl material */
1800                         glMaterialfv(GL_FRONT_AND_BACK, GL_DIFFUSE, GMS.matbuf[nr].diff);
1801                         glMaterialfv(GL_FRONT_AND_BACK, GL_SPECULAR, GMS.matbuf[nr].spec);
1802                         glMateriali(GL_FRONT_AND_BACK, GL_SHININESS, GMS.matbuf[nr].hard);
1803                 }
1804
1805                 /* set (alpha) blending mode */
1806                 GPU_set_material_alpha_blend(alphablend);
1807         }
1808
1809         return GMS.lastretval;
1810 }
1811
1812 void GPU_set_material_alpha_blend(int alphablend)
1813 {
1814         if (GMS.lastalphablend == alphablend)
1815                 return;
1816         
1817         gpu_set_alpha_blend(alphablend);
1818         GMS.lastalphablend = alphablend;
1819 }
1820
1821 int GPU_get_material_alpha_blend(void)
1822 {
1823         return GMS.lastalphablend;
1824 }
1825
1826 void GPU_disable_material(void)
1827 {
1828         GMS.lastmatnr = -1;
1829         GMS.lastretval = 1;
1830
1831         if (GMS.gboundmat) {
1832                 if (GMS.backface_culling)
1833                         glDisable(GL_CULL_FACE);
1834
1835                 if (GMS.is_alpha_pass) glDepthMask(0);
1836                 GPU_material_unbind(GPU_material_from_blender(GMS.gscene, GMS.gboundmat, GMS.is_opensubdiv));
1837                 GMS.gboundmat = NULL;
1838         }
1839
1840         GPU_set_material_alpha_blend(GPU_BLEND_SOLID);
1841 }
1842
1843 void GPU_material_diffuse_get(int nr, float diff[4])
1844 {
1845         /* prevent index to use un-initialized array items */
1846         if (nr >= GMS.totmat)
1847                 nr = 0;
1848
1849         /* no GPU_begin_object_materials, use default material */
1850         if (!GMS.matbuf) {
1851                 mul_v3_v3fl(diff, &defmaterial.r, defmaterial.ref + defmaterial.emit);
1852         }
1853         else {
1854                 copy_v4_v4(diff, GMS.matbuf[nr].diff);
1855         }
1856 }
1857
1858 bool GPU_material_use_matcaps_get(void)
1859 {
1860         return GMS.use_matcaps;
1861 }
1862
1863 bool GPU_object_materials_check(void)
1864 {
1865         return GMS.is_enabled;
1866 }
1867
1868 void GPU_end_object_materials(void)
1869 {
1870         GPU_disable_material();
1871
1872         GMS.is_enabled = false;
1873
1874         if (GMS.matbuf && GMS.matbuf != GMS.matbuf_fixed) {
1875                 MEM_freeN(GMS.matbuf);
1876                 MEM_freeN(GMS.gmatbuf);
1877                 MEM_freeN(GMS.alphablend);
1878         }
1879
1880         GMS.matbuf = NULL;
1881         GMS.gmatbuf = NULL;
1882         GMS.alphablend = NULL;
1883
1884         /* resetting the texture matrix after the scaling needed for tiled textures */
1885         if (GTS.tilemode) {
1886                 glMatrixMode(GL_TEXTURE);
1887                 glLoadIdentity();
1888                 glMatrixMode(GL_MODELVIEW);
1889         }
1890 }
1891
1892 /* Lights */
1893
1894 int GPU_default_lights(void)
1895 {
1896         float zero[4] = {0.0f, 0.0f, 0.0f, 0.0f}, position[4];
1897         int a, count = 0;
1898         
1899         /* initialize */
1900         if (U.light[0].flag == 0 && U.light[1].flag == 0 && U.light[2].flag == 0) {
1901                 U.light[0].flag = 1;
1902                 U.light[0].vec[0] = -0.3; U.light[0].vec[1] = 0.3; U.light[0].vec[2] = 0.9;
1903                 U.light[0].col[0] = 0.8; U.light[0].col[1] = 0.8; U.light[0].col[2] = 0.8;
1904                 U.light[0].spec[0] = 0.5; U.light[0].spec[1] = 0.5; U.light[0].spec[2] = 0.5;
1905                 U.light[0].spec[3] = 1.0;
1906                 
1907                 U.light[1].flag = 0;
1908                 U.light[1].vec[0] = 0.5; U.light[1].vec[1] = 0.5; U.light[1].vec[2] = 0.1;
1909                 U.light[1].col[0] = 0.4; U.light[1].col[1] = 0.4; U.light[1].col[2] = 0.8;
1910                 U.light[1].spec[0] = 0.3; U.light[1].spec[1] = 0.3; U.light[1].spec[2] = 0.5;
1911                 U.light[1].spec[3] = 1.0;
1912         
1913                 U.light[2].flag = 0;
1914                 U.light[2].vec[0] = 0.3; U.light[2].vec[1] = -0.3; U.light[2].vec[2] = -0.2;
1915                 U.light[2].col[0] = 0.8; U.light[2].col[1] = 0.5; U.light[2].col[2] = 0.4;
1916                 U.light[2].spec[0] = 0.5; U.light[2].spec[1] = 0.4; U.light[2].spec[2] = 0.3;
1917                 U.light[2].spec[3] = 1.0;
1918         }
1919
1920         glLightModeli(GL_LIGHT_MODEL_LOCAL_VIEWER, GL_FALSE);
1921
1922         for (a = 0; a < 8; a++) {
1923                 if (a < 3) {
1924                         if (U.light[a].flag) {
1925                                 glEnable(GL_LIGHT0 + a);
1926
1927                                 normalize_v3_v3(position, U.light[a].vec);
1928                                 position[3] = 0.0f;
1929                                 
1930                                 glLightfv(GL_LIGHT0 + a, GL_POSITION, position); 
1931                                 glLightfv(GL_LIGHT0 + a, GL_DIFFUSE, U.light[a].col); 
1932                                 glLightfv(GL_LIGHT0 + a, GL_SPECULAR, U.light[a].spec); 
1933
1934                                 count++;
1935                         }
1936                         else {
1937                                 glDisable(GL_LIGHT0 + a);
1938
1939                                 glLightfv(GL_LIGHT0 + a, GL_POSITION, zero); 
1940                                 glLightfv(GL_LIGHT0 + a, GL_DIFFUSE, zero); 
1941                                 glLightfv(GL_LIGHT0 + a, GL_SPECULAR, zero);
1942                         }
1943
1944                         /* clear stuff from other opengl lamp usage */
1945                         glLightf(GL_LIGHT0 + a, GL_SPOT_CUTOFF, 180.0);
1946                         glLightf(GL_LIGHT0 + a, GL_CONSTANT_ATTENUATION, 1.0);
1947                         glLightf(GL_LIGHT0 + a, GL_LINEAR_ATTENUATION, 0.0);
1948                 }
1949                 else
1950                         glDisable(GL_LIGHT0 + a);
1951         }
1952         
1953         glDisable(GL_LIGHTING);
1954
1955         glDisable(GL_COLOR_MATERIAL);
1956
1957         return count;
1958 }
1959
1960 int GPU_scene_object_lights(Scene *scene, Object *ob, int lay, float viewmat[4][4], int ortho)
1961 {
1962         Base *base;
1963         Lamp *la;
1964         int count;
1965         float position[4], direction[4], energy[4];
1966         
1967         /* disable all lights */
1968         for (count = 0; count < 8; count++)
1969                 glDisable(GL_LIGHT0 + count);
1970         
1971         /* view direction for specular is not computed correct by default in
1972          * opengl, so we set the settings ourselfs */
1973         glLightModeli(GL_LIGHT_MODEL_LOCAL_VIEWER, ortho ? GL_FALSE : GL_TRUE);
1974
1975         count = 0;
1976
1977         for (base = scene->base.first; base; base = base->next) {
1978                 if (base->object->type != OB_LAMP)
1979                         continue;
1980
1981                 if (!(base->lay & lay) || !(base->lay & ob->lay))
1982                         continue;
1983
1984                 la = base->object->data;
1985                 
1986                 /* setup lamp transform */
1987                 glPushMatrix();
1988                 glLoadMatrixf((float *)viewmat);
1989                 
1990                 if (la->type == LA_SUN) {
1991                         /* sun lamp */
1992                         copy_v3_v3(direction, base->object->obmat[2]);
1993                         direction[3] = 0.0;
1994
1995                         glLightfv(GL_LIGHT0+count, GL_POSITION, direction); 
1996                 }
1997                 else {
1998                         /* other lamps with attenuation */
1999                         copy_v3_v3(position, base->object->obmat[3]);
2000                         position[3] = 1.0f;
2001
2002                         glLightfv(GL_LIGHT0+count, GL_POSITION, position); 
2003                         glLightf(GL_LIGHT0+count, GL_CONSTANT_ATTENUATION, 1.0);
2004                         glLightf(GL_LIGHT0+count, GL_LINEAR_ATTENUATION, la->att1 / la->dist);
2005                         glLightf(GL_LIGHT0+count, GL_QUADRATIC_ATTENUATION, la->att2 / (la->dist * la->dist));
2006                         
2007                         if (la->type == LA_SPOT) {
2008                                 /* spot lamp */
2009                                 negate_v3_v3(direction, base->object->obmat[2]);
2010                                 glLightfv(GL_LIGHT0 + count, GL_SPOT_DIRECTION, direction);
2011                                 glLightf(GL_LIGHT0 + count, GL_SPOT_CUTOFF, RAD2DEGF(la->spotsize * 0.5f));
2012                                 glLightf(GL_LIGHT0 + count, GL_SPOT_EXPONENT, 128.0f * la->spotblend);
2013                         }
2014                         else
2015                                 glLightf(GL_LIGHT0 + count, GL_SPOT_CUTOFF, 180.0);
2016                 }
2017                 
2018                 /* setup energy */
2019                 mul_v3_v3fl(energy, &la->r, la->energy);
2020                 energy[3] = 1.0;
2021
2022                 glLightfv(GL_LIGHT0 + count, GL_DIFFUSE, energy); 
2023                 glLightfv(GL_LIGHT0 + count, GL_SPECULAR, energy);
2024                 glEnable(GL_LIGHT0 + count);
2025                 
2026                 glPopMatrix();
2027                 
2028                 count++;
2029                 if (count == 8)
2030                         break;
2031         }
2032
2033         return count;
2034 }
2035
2036 static void gpu_multisample(bool enable)
2037 {
2038         if (GLEW_VERSION_1_3 || GLEW_ARB_multisample) {
2039 #ifdef __linux__
2040                 /* changing multisample from the default (enabled) causes problems on some
2041                  * systems (NVIDIA/Linux) when the pixel format doesn't have a multisample buffer */
2042                 bool toggle_ok = true;
2043
2044                 if (GPU_type_matches(GPU_DEVICE_NVIDIA, GPU_OS_UNIX, GPU_DRIVER_ANY)) {
2045                         int samples = 0;
2046                         glGetIntegerv(GL_SAMPLES, &samples);
2047
2048                         if (samples == 0)
2049                                 toggle_ok = false;
2050                 }
2051
2052                 if (toggle_ok) {
2053                         if (enable)
2054                                 glEnable(GL_MULTISAMPLE);
2055                         else
2056                                 glDisable(GL_MULTISAMPLE);
2057                 }
2058 #else
2059                 if (enable)
2060                         glEnable(GL_MULTISAMPLE);
2061                 else
2062                         glDisable(GL_MULTISAMPLE);
2063 #endif
2064         }
2065 }
2066
2067 /* Default OpenGL State */
2068
2069 void GPU_state_init(void)
2070 {
2071         /* also called when doing opengl rendering and in the game engine */
2072         float mat_ambient[] = { 0.0, 0.0, 0.0, 0.0 };
2073         float mat_specular[] = { 0.5, 0.5, 0.5, 1.0 };
2074         int a, x, y;
2075         GLubyte pat[32 * 32];
2076         const GLubyte *patc = pat;
2077         
2078         glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT, mat_ambient);
2079         glMaterialfv(GL_FRONT_AND_BACK, GL_DIFFUSE, mat_specular);
2080         glMaterialfv(GL_FRONT_AND_BACK, GL_SPECULAR, mat_specular);
2081         glMateriali(GL_FRONT_AND_BACK, GL_SHININESS, 35);
2082
2083         GPU_default_lights();
2084         
2085         glDepthFunc(GL_LEQUAL);
2086         /* scaling matrices */
2087         glEnable(GL_NORMALIZE);
2088
2089         glShadeModel(GL_FLAT);
2090
2091         glDisable(GL_ALPHA_TEST);
2092         glDisable(GL_BLEND);
2093         glDisable(GL_DEPTH_TEST);
2094         glDisable(GL_FOG);
2095         glDisable(GL_LIGHTING);
2096         glDisable(GL_LOGIC_OP);
2097         glDisable(GL_STENCIL_TEST);
2098         glDisable(GL_TEXTURE_1D);
2099         glDisable(GL_TEXTURE_2D);
2100
2101         /* default disabled, enable should be local per function */
2102         glDisableClientState(GL_VERTEX_ARRAY);
2103         glDisableClientState(GL_NORMAL_ARRAY);
2104         glDisableClientState(GL_COLOR_ARRAY);
2105         glDisableClientState(GL_TEXTURE_COORD_ARRAY);
2106         
2107         glPixelTransferi(GL_MAP_COLOR, GL_FALSE);
2108         glPixelTransferi(GL_RED_SCALE, 1);
2109         glPixelTransferi(GL_RED_BIAS, 0);
2110         glPixelTransferi(GL_GREEN_SCALE, 1);
2111         glPixelTransferi(GL_GREEN_BIAS, 0);
2112         glPixelTransferi(GL_BLUE_SCALE, 1);
2113         glPixelTransferi(GL_BLUE_BIAS, 0);
2114         glPixelTransferi(GL_ALPHA_SCALE, 1);
2115         glPixelTransferi(GL_ALPHA_BIAS, 0);
2116         
2117         glPixelTransferi(GL_DEPTH_BIAS, 0);
2118         glPixelTransferi(GL_DEPTH_SCALE, 1);
2119         glDepthRange(0.0, 1.0);
2120         
2121         a = 0;
2122         for (x = 0; x < 32; x++) {
2123                 for (y = 0; y < 4; y++) {
2124                         if (x & 1) pat[a++] = 0x88;
2125                         else pat[a++] = 0x22;
2126                 }
2127         }
2128
2129         glPolygonStipple(patc);
2130
2131         glMatrixMode(GL_TEXTURE);
2132         glLoadIdentity();
2133         glMatrixMode(GL_MODELVIEW);
2134
2135         glFrontFace(GL_CCW);
2136         glCullFace(GL_BACK);
2137         glDisable(GL_CULL_FACE);
2138
2139         gpu_multisample(false);
2140 }
2141
2142 #ifdef WITH_OPENSUBDIV
2143 /* Update face-varying variables offset which might be
2144  * different from mesh to mesh sharing the same material.
2145  */
2146 void GPU_draw_update_fvar_offset(DerivedMesh *dm)
2147 {
2148         int i;
2149
2150         /* Sanity check to be sure we only do this for OpenSubdiv draw. */
2151         BLI_assert(dm->type == DM_TYPE_CCGDM);
2152         BLI_assert(GMS.is_opensubdiv);
2153
2154         for (i = 0; i < GMS.totmat; ++i) {
2155                 Material *material = GMS.gmatbuf[i];
2156                 GPUMaterial *gpu_material;
2157
2158                 if (material == NULL) {
2159                         continue;
2160                 }
2161
2162                 gpu_material = GPU_material_from_blender(GMS.gscene,
2163                                                          material,
2164                                                          GMS.is_opensubdiv);
2165
2166                 GPU_material_update_fvar_offset(gpu_material, dm);
2167         }
2168 }
2169 #endif