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