2.5: Image Editor
[blender-staging.git] / source / blender / gpu / intern / gpu_draw.c
1 /**
2  * $Id$
3  *
4  * ***** BEGIN GPL LICENSE BLOCK *****
5  *
6  * This program is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU General Public License
8  * as published by the Free Software Foundation; either version 2
9  * of the License, or (at your option) any later version. The Blender
10  * Foundation also sells licenses for use in proprietary software under
11  * the Blender License.  See http://www.blender.org/BL/ for information
12  * about this.
13  *
14  * This program is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17  * GNU General Public License for more details.
18  *
19  * You should have received a copy of the GNU General Public License
20  * along with this program; if not, write to the Free Software Foundation,
21  * Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
22  *
23  * The Original Code is Copyright (C) 2005 Blender Foundation.
24  * All rights reserved.
25  *
26  * The Original Code is: all of this file.
27  *
28  * Contributor(s): Brecht Van Lommel.
29  *
30  * ***** END GPL LICENSE BLOCK *****
31  */
32
33 #include <string.h>
34
35 #include "GL/glew.h"
36
37 #include "DNA_image_types.h"
38 #include "DNA_lamp_types.h"
39 #include "DNA_material_types.h"
40 #include "DNA_meshdata_types.h"
41 #include "DNA_node_types.h"
42 #include "DNA_object_types.h"
43 #include "DNA_scene_types.h"
44 #include "DNA_userdef_types.h"
45 #include "DNA_view3d_types.h"
46
47 #include "MEM_guardedalloc.h"
48
49 #include "IMB_imbuf.h"
50 #include "IMB_imbuf_types.h"
51
52 #include "BKE_bmfont.h"
53 #include "BKE_global.h"
54 #include "BKE_image.h"
55 #include "BKE_main.h"
56 #include "BKE_material.h"
57 #include "BKE_node.h"
58 #include "BKE_object.h"
59 #include "BKE_utildefines.h"
60
61 #include "GPU_extensions.h"
62 #include "GPU_material.h"
63 #include "GPU_draw.h"
64
65 /* These are some obscure rendering functions shared between the
66  * game engine and the blender, in this module to avoid duplicaten
67  * and abstract them away from the rest a bit */
68
69 /* Text Rendering */
70
71 static void gpu_mcol(unsigned int ucol)
72 {
73         /* mcol order is swapped */
74         char *cp= (char *)&ucol;
75         glColor3ub(cp[3], cp[2], cp[1]);
76 }
77
78 void GPU_render_text(MTFace *tface, int mode,
79         const char *textstr, int textlen, unsigned int *col,
80         float *v1, float *v2, float *v3, float *v4, int glattrib)
81 {
82         if ((mode & TF_BMFONT) && (textlen>0) && tface->tpage) {
83                 Image* ima = (Image*)tface->tpage;
84                 int index, character;
85                 float centerx, centery, sizex, sizey, transx, transy, movex, movey, advance;
86                 float advance_tab;
87                 
88                 /* multiline */
89                 float line_start= 0.0f, line_height;
90                 
91                 if (v4)
92                         line_height= MAX4(v1[1], v2[1], v3[1], v4[2]) - MIN4(v1[1], v2[1], v3[1], v4[2]);
93                 else
94                         line_height= MAX3(v1[1], v2[1], v3[1]) - MIN3(v1[1], v2[1], v3[1]);
95                 line_height *= 1.2; /* could be an option? */
96                 /* end multiline */
97
98                 
99                 /* color has been set */
100                 if (tface->mode & TF_OBCOL)
101                         col= NULL;
102                 else if (!col)
103                         glColor3f(1.0f, 1.0f, 1.0f);
104
105                 glPushMatrix();
106                 
107                 /* get the tab width */
108                 matrixGlyph((ImBuf *)ima->ibufs.first, ' ', & centerx, &centery,
109                         &sizex, &sizey, &transx, &transy, &movex, &movey, &advance);
110                 
111                 advance_tab= advance * 4; /* tab width could also be an option */
112                 
113                 
114                 for (index = 0; index < textlen; index++) {
115                         float uv[4][2];
116
117                         // lets calculate offset stuff
118                         character = textstr[index];
119                         
120                         if (character=='\n') {
121                                 glTranslatef(line_start, -line_height, 0.0);
122                                 line_start = 0.0f;
123                                 continue;
124                         }
125                         else if (character=='\t') {
126                                 glTranslatef(advance_tab, 0.0, 0.0);
127                                 line_start -= advance_tab; /* so we can go back to the start of the line */
128                                 continue;
129                                 
130                         }
131                         
132                         // space starts at offset 1
133                         // character = character - ' ' + 1;
134                         matrixGlyph((ImBuf *)ima->ibufs.first, character, & centerx, &centery,
135                                 &sizex, &sizey, &transx, &transy, &movex, &movey, &advance);
136
137                         uv[0][0] = (tface->uv[0][0] - centerx) * sizex + transx;
138                         uv[0][1] = (tface->uv[0][1] - centery) * sizey + transy;
139                         uv[1][0] = (tface->uv[1][0] - centerx) * sizex + transx;
140                         uv[1][1] = (tface->uv[1][1] - centery) * sizey + transy;
141                         uv[2][0] = (tface->uv[2][0] - centerx) * sizex + transx;
142                         uv[2][1] = (tface->uv[2][1] - centery) * sizey + transy;
143                         
144                         glBegin(GL_POLYGON);
145                         if(glattrib >= 0) glVertexAttrib2fvARB(glattrib, uv[0]);
146                         else glTexCoord2fv(uv[0]);
147                         if(col) gpu_mcol(col[0]);
148                         glVertex3f(sizex * v1[0] + movex, sizey * v1[1] + movey, v1[2]);
149                         
150                         if(glattrib >= 0) glVertexAttrib2fvARB(glattrib, uv[1]);
151                         else glTexCoord2fv(uv[1]);
152                         if(col) gpu_mcol(col[1]);
153                         glVertex3f(sizex * v2[0] + movex, sizey * v2[1] + movey, v2[2]);
154
155                         if(glattrib >= 0) glVertexAttrib2fvARB(glattrib, uv[2]);
156                         else glTexCoord2fv(uv[2]);
157                         if(col) gpu_mcol(col[2]);
158                         glVertex3f(sizex * v3[0] + movex, sizey * v3[1] + movey, v3[2]);
159
160                         if(v4) {
161                                 uv[3][0] = (tface->uv[3][0] - centerx) * sizex + transx;
162                                 uv[3][1] = (tface->uv[3][1] - centery) * sizey + transy;
163
164                                 if(glattrib >= 0) glVertexAttrib2fvARB(glattrib, uv[3]);
165                                 else glTexCoord2fv(uv[3]);
166                                 if(col) gpu_mcol(col[3]);
167                                 glVertex3f(sizex * v4[0] + movex, sizey * v4[1] + movey, v4[2]);
168                         }
169                         glEnd();
170
171                         glTranslatef(advance, 0.0, 0.0);
172                         line_start -= advance; /* so we can go back to the start of the line */
173                 }
174                 glPopMatrix();
175         }
176 }
177
178 /* Checking powers of two for images since opengl 1.x requires it */
179
180 static int is_pow2(int num)
181 {
182         /* (n&(n-1)) zeros the least significant bit of n */
183         return ((num)&(num-1))==0;
184 }
185
186 static int smaller_pow2(int num)
187 {
188         while (!is_pow2(num))
189                 num= num&(num-1);
190
191         return num;     
192 }
193
194 static int is_pow2_limit(int num)
195 {
196         /* take texture clamping into account */
197         if (G.f & G_TEXTUREPAINT)
198                 return 1;
199         if (U.glreslimit != 0 && num > U.glreslimit)
200                 return 0;
201
202         return ((num)&(num-1))==0;
203 }
204
205 static int smaller_pow2_limit(int num)
206 {
207         if (G.f & G_TEXTUREPAINT)
208                 return 1;
209         
210         /* take texture clamping into account */
211         if (U.glreslimit != 0 && num > U.glreslimit)
212                 return U.glreslimit;
213
214         return smaller_pow2(num);
215 }
216
217 /* Current OpenGL state caching for GPU_set_tpage */
218
219 static struct GPUTextureState {
220         int curtile, tile;
221         int curtilemode, tilemode;
222         int curtileXRep, tileXRep;
223         int curtileYRep, tileYRep;
224         Image *ima, *curima;
225
226         int domipmap, linearmipmap;
227
228         int alphamode;
229         MTFace *lasttface;
230 } GTS = {0, 0, 0, 0, 0, 0, 0, 0, NULL, NULL, 1, 0, -1, NULL};
231
232 /* Mipmap settings */
233
234 void GPU_set_mipmap(int mipmap)
235 {
236         if (GTS.domipmap != (mipmap != 0)) {
237                 GPU_free_images();
238                 GTS.domipmap = mipmap != 0;
239         }
240 }
241
242 void GPU_set_linear_mipmap(int linear)
243 {
244         if (GTS.linearmipmap != (linear != 0)) {
245                 GPU_free_images();
246                 GTS.linearmipmap = linear != 0;
247         }
248 }
249
250 static int gpu_get_mipmap(void)
251 {
252         return GTS.domipmap && (!(G.f & G_TEXTUREPAINT));
253 }
254
255 static GLenum gpu_get_mipmap_filter(int mag)
256 {
257         /* linearmipmap is off by default *when mipmapping is off,
258          * use unfiltered display */
259         if(mag) {
260                 if(GTS.linearmipmap || GTS.domipmap)
261                         return GL_LINEAR;
262                 else
263                         return GL_NEAREST;
264         }
265         else {
266                 if(GTS.linearmipmap)
267                         return GL_LINEAR_MIPMAP_LINEAR;
268                 else if(GTS.domipmap)
269                         return GL_LINEAR_MIPMAP_NEAREST;
270                 else
271                         return GL_NEAREST;
272         }
273 }
274
275 /* Set OpenGL state for an MTFace */
276
277 static void gpu_make_repbind(Image *ima)
278 {
279         ImBuf *ibuf;
280         
281         ibuf = BKE_image_get_ibuf(ima, NULL);
282         if(ibuf==NULL)
283                 return;
284
285         if(ima->repbind) {
286                 glDeleteTextures(ima->totbind, (GLuint *)ima->repbind);
287                 MEM_freeN(ima->repbind);
288                 ima->repbind= 0;
289                 ima->tpageflag &= ~IMA_MIPMAP_COMPLETE;
290         }
291
292         ima->totbind= ima->xrep*ima->yrep;
293
294         if(ima->totbind>1)
295                 ima->repbind= MEM_callocN(sizeof(int)*ima->totbind, "repbind");
296 }
297
298 static void gpu_clear_tpage()
299 {
300         if(GTS.lasttface==0)
301                 return;
302         
303         GTS.lasttface= 0;
304         GTS.curtile= 0;
305         GTS.curima= 0;
306         if(GTS.curtilemode!=0) {
307                 glMatrixMode(GL_TEXTURE);
308                 glLoadIdentity();
309                 glMatrixMode(GL_MODELVIEW);
310         }
311         GTS.curtilemode= 0;
312         GTS.curtileXRep=0;
313         GTS.curtileYRep=0;
314         GTS.alphamode= -1;
315         
316         glDisable(GL_BLEND);
317         glDisable(GL_TEXTURE_2D);
318         glDisable(GL_TEXTURE_GEN_S);
319         glDisable(GL_TEXTURE_GEN_T);
320         glDisable(GL_ALPHA_TEST);
321 }
322
323 static void gpu_set_blend_mode(GPUBlendMode blendmode)
324 {
325         if(blendmode == GPU_BLEND_SOLID) {
326                 glDisable(GL_BLEND);
327                 glDisable(GL_ALPHA_TEST);
328                 glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
329         }
330         else if(blendmode==GPU_BLEND_ADD) {
331                 glEnable(GL_BLEND);
332                 glBlendFunc(GL_ONE, GL_ONE);
333                 glDisable(GL_ALPHA_TEST);
334         }
335         else if(blendmode==GPU_BLEND_ALPHA) {
336                 glEnable(GL_BLEND);
337                 glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
338                 
339                 /* if U.glalphaclip == 1.0, some cards go bonkers...
340                  * turn off alpha test in this case */
341
342                 /* added after 2.45 to clip alpha */
343                 if(U.glalphaclip == 1.0) {
344                         glDisable(GL_ALPHA_TEST);
345                 }
346                 else {
347                         glEnable(GL_ALPHA_TEST);
348                         glAlphaFunc(GL_GREATER, U.glalphaclip);
349                 }
350         }
351         else if(blendmode==GPU_BLEND_CLIP) {
352                 glDisable(GL_BLEND); 
353                 glEnable(GL_ALPHA_TEST);
354                 glAlphaFunc(GL_GREATER, 0.5f);
355         }
356 }
357
358 static void gpu_verify_alpha_mode(MTFace *tface)
359 {
360         /* verify alpha blending modes */
361         if(GTS.alphamode == tface->transp)
362                 return;
363
364         gpu_set_blend_mode(tface->transp);
365         GTS.alphamode= tface->transp;
366 }
367
368 static void gpu_verify_reflection(Image *ima)
369 {
370         if (ima && (ima->flag & IMA_REFLECT)) {
371                 /* enable reflection mapping */
372                 glTexGeni(GL_S, GL_TEXTURE_GEN_MODE, GL_SPHERE_MAP);
373                 glTexGeni(GL_T, GL_TEXTURE_GEN_MODE, GL_SPHERE_MAP);
374
375                 glEnable(GL_TEXTURE_GEN_S);
376                 glEnable(GL_TEXTURE_GEN_T);
377         }
378         else {
379                 /* disable reflection mapping */
380                 glDisable(GL_TEXTURE_GEN_S);
381                 glDisable(GL_TEXTURE_GEN_T);
382         }
383 }
384
385 int GPU_verify_image(Image *ima, int tftile, int tfmode, int compare)
386 {
387         ImBuf *ibuf = NULL;
388         unsigned int *bind = NULL;
389         int rectw, recth, tpx=0, tpy=0, y;
390         unsigned int *rectrow, *tilerectrow;
391         unsigned int *tilerect= NULL, *scalerect= NULL, *rect= NULL;
392         short texwindx, texwindy, texwinsx, texwinsy;
393
394         /* initialize tile mode and number of repeats */
395         GTS.ima = ima;
396         GTS.tilemode= (ima && (ima->tpageflag & (IMA_TILES|IMA_TWINANIM)));
397         GTS.tileXRep = 0;
398         GTS.tileYRep = 0;
399
400         /* setting current tile according to frame */
401         if(ima && (ima->tpageflag & IMA_TWINANIM))
402                 GTS.tile= ima->lastframe;
403         else
404                 GTS.tile= tftile;
405
406         GTS.tile = MAX2(0, GTS.tile);
407
408         if(ima) {
409                 GTS.tileXRep = ima->xrep;
410                 GTS.tileYRep = ima->yrep;
411         }
412
413         /* if same image & tile, we're done */
414         if(compare && ima == GTS.curima && GTS.curtile == GTS.tile &&
415            GTS.tilemode == GTS.curtilemode && GTS.curtileXRep == GTS.tileXRep &&
416            GTS.curtileYRep == GTS.tileYRep)
417                 return (ima!=0);
418
419         /* if tiling mode or repeat changed, change texture matrix to fit */
420         if(GTS.tilemode!=GTS.curtilemode || GTS.curtileXRep!=GTS.tileXRep ||
421            GTS.curtileYRep != GTS.tileYRep) {
422
423                 glMatrixMode(GL_TEXTURE);
424                 glLoadIdentity();
425
426                 if(ima && (ima->tpageflag & IMA_TILES))
427                         glScalef(ima->xrep, ima->yrep, 1.0);
428
429                 glMatrixMode(GL_MODELVIEW);
430         }
431
432         /* check if we have a valid image */
433         if(ima==NULL || ima->ok==0)
434                 return 0;
435
436         /* check if we have a valid image buffer */
437         ibuf= BKE_image_get_ibuf(ima, NULL);
438
439         if(ibuf==NULL)
440                 return 0;
441
442         /* ensure we have a char buffer and not only float */
443         if ((ibuf->rect==NULL) && ibuf->rect_float)
444                 IMB_rect_from_float(ibuf);
445
446         if(GTS.tilemode) {
447                 /* tiled mode */
448                 if(ima->repbind==0) gpu_make_repbind(ima);
449                 if(GTS.tile>=ima->totbind) GTS.tile= 0;
450                 
451                 /* this happens when you change repeat buttons */
452                 if(ima->repbind) bind= &ima->repbind[GTS.tile];
453                 else bind= &ima->bindcode;
454                 
455                 if(*bind==0) {
456                         
457                         texwindx= ibuf->x/ima->xrep;
458                         texwindy= ibuf->y/ima->yrep;
459                         
460                         if(GTS.tile>=ima->xrep*ima->yrep)
461                                 GTS.tile= ima->xrep*ima->yrep-1;
462         
463                         texwinsy= GTS.tile / ima->xrep;
464                         texwinsx= GTS.tile - texwinsy*ima->xrep;
465         
466                         texwinsx*= texwindx;
467                         texwinsy*= texwindy;
468         
469                         tpx= texwindx;
470                         tpy= texwindy;
471
472                         rect= ibuf->rect + texwinsy*ibuf->x + texwinsx;
473                 }
474         }
475         else {
476                 /* regular image mode */
477                 bind= &ima->bindcode;
478                 
479                 if(*bind==0) {
480                         tpx= ibuf->x;
481                         tpy= ibuf->y;
482                         rect= ibuf->rect;
483                 }
484         }
485
486         if(*bind != 0) {
487                 /* enable opengl drawing with textures */
488                 glBindTexture(GL_TEXTURE_2D, *bind);
489                 return *bind;
490         }
491
492         rectw = tpx;
493         recth = tpy;
494
495         /* for tiles, copy only part of image into buffer */
496         if (GTS.tilemode) {
497                 tilerect= MEM_mallocN(rectw*recth*sizeof(*tilerect), "tilerect");
498
499                 for (y=0; y<recth; y++) {
500                         rectrow= &rect[y*ibuf->x];
501                         tilerectrow= &tilerect[y*rectw];
502                                 
503                         memcpy(tilerectrow, rectrow, tpx*sizeof(*rectrow));
504                 }
505                         
506                 rect= tilerect;
507         }
508
509         /* scale if not a power of two */
510         if (!is_pow2_limit(rectw) || !is_pow2_limit(recth)) {
511                 rectw= smaller_pow2_limit(rectw);
512                 recth= smaller_pow2_limit(recth);
513                 
514                 scalerect= MEM_mallocN(rectw*recth*sizeof(*scalerect), "scalerect");
515                 gluScaleImage(GL_RGBA, tpx, tpy, GL_UNSIGNED_BYTE, rect, rectw, recth, GL_UNSIGNED_BYTE, scalerect);
516                 rect= scalerect;
517         }
518
519         /* create image */
520         glGenTextures(1, (GLuint *)bind);
521         glBindTexture( GL_TEXTURE_2D, *bind);
522
523         if (!gpu_get_mipmap()) {
524                 glTexImage2D(GL_TEXTURE_2D, 0,  GL_RGBA,  rectw, recth, 0, GL_RGBA, GL_UNSIGNED_BYTE, rect);
525                 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
526                 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, gpu_get_mipmap_filter(1));
527         }
528         else {
529                 gluBuild2DMipmaps(GL_TEXTURE_2D, GL_RGBA, rectw, recth, GL_RGBA, GL_UNSIGNED_BYTE, rect);
530                 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, gpu_get_mipmap_filter(0));
531                 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, gpu_get_mipmap_filter(1));
532
533                 ima->tpageflag |= IMA_MIPMAP_COMPLETE;
534         }
535
536         /* set to modulate with vertex color */
537         glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);
538                 
539         /* clean up */
540         if (tilerect)
541                 MEM_freeN(tilerect);
542         if (scalerect)
543                 MEM_freeN(scalerect);
544
545         return *bind;
546 }
547
548 static void gpu_verify_repeat(Image *ima)
549 {
550         /* set either clamp or repeat in X/Y */
551         if (ima->tpageflag & IMA_CLAMP_U)
552            glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
553         else
554                 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
555
556         if (ima->tpageflag & IMA_CLAMP_V)
557                 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
558         else
559                 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
560 }
561
562 int GPU_set_tpage(MTFace *tface)
563 {
564         Image *ima;
565         
566         /* check if we need to clear the state */
567         if(tface==0) {
568                 gpu_clear_tpage();
569                 return 0;
570         }
571
572         ima= tface->tpage;
573         GTS.lasttface= tface;
574
575         gpu_verify_alpha_mode(tface);
576         gpu_verify_reflection(ima);
577
578         if(GPU_verify_image(ima, tface->tile, tface->mode, 1)) {
579                 GTS.curtile= GTS.tile;
580                 GTS.curima= GTS.ima;
581                 GTS.curtilemode= GTS.tilemode;
582                 GTS.curtileXRep = GTS.tileXRep;
583                 GTS.curtileYRep = GTS.tileYRep;
584
585                 glEnable(GL_TEXTURE_2D);
586         }
587         else {
588                 glDisable(GL_TEXTURE_2D);
589                 
590                 GTS.curtile= 0;
591                 GTS.curima= 0;
592                 GTS.curtilemode= 0;
593                 GTS.curtileXRep = 0;
594                 GTS.curtileYRep = 0;
595
596                 return 0;
597         }
598         
599         gpu_verify_repeat(ima);
600         
601         /* Did this get lost in the image recode? */
602         /* tag_image_time(ima);*/
603
604         return 1;
605 }
606
607 /* these two functions are called on entering and exiting texture paint mode,
608    temporary disabling/enabling mipmapping on all images for quick texture
609    updates with glTexSubImage2D. images that didn't change don't have to be
610    re-uploaded to OpenGL */
611 void GPU_paint_set_mipmap(int mipmap)
612 {
613         Image* ima;
614         
615         if(!GTS.domipmap)
616                 return;
617
618         if(mipmap) {
619                 for(ima=G.main->image.first; ima; ima=ima->id.next) {
620                         if(ima->bindcode) {
621                                 if(ima->tpageflag & IMA_MIPMAP_COMPLETE) {
622                                         glBindTexture(GL_TEXTURE_2D, ima->bindcode);
623                                         glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, gpu_get_mipmap_filter(0));
624                                         glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, gpu_get_mipmap_filter(1));
625                                 }
626                                 else
627                                         GPU_free_image(ima);
628                         }
629                 }
630
631         }
632         else {
633                 for(ima=G.main->image.first; ima; ima=ima->id.next) {
634                         if(ima->bindcode) {
635                                 glBindTexture(GL_TEXTURE_2D, ima->bindcode);
636                                 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
637                                 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, gpu_get_mipmap_filter(1));
638                         }
639                 }
640         }
641 }
642
643 void GPU_paint_update_image(Image *ima, int x, int y, int w, int h)
644 {
645         ImBuf *ibuf;
646         
647         ibuf = BKE_image_get_ibuf(ima, NULL);
648         
649         if (ima->repbind || gpu_get_mipmap() || !ima->bindcode || !ibuf ||
650                 (!is_pow2(ibuf->x) || !is_pow2(ibuf->y)) ||
651                 (w == 0) || (h == 0)) {
652                 /* these cases require full reload still */
653                 GPU_free_image(ima);
654         }
655         else {
656                 /* for the special case, we can do a partial update
657                  * which is much quicker for painting */
658                 GLint row_length, skip_pixels, skip_rows;
659
660                 glGetIntegerv(GL_UNPACK_ROW_LENGTH, &row_length);
661                 glGetIntegerv(GL_UNPACK_SKIP_PIXELS, &skip_pixels);
662                 glGetIntegerv(GL_UNPACK_SKIP_ROWS, &skip_rows);
663
664                 if ((ibuf->rect==NULL) && ibuf->rect_float)
665                         IMB_rect_from_float(ibuf);
666
667                 glBindTexture(GL_TEXTURE_2D, ima->bindcode);
668
669                 glPixelStorei(GL_UNPACK_ROW_LENGTH, ibuf->x);
670                 glPixelStorei(GL_UNPACK_SKIP_PIXELS, x);
671                 glPixelStorei(GL_UNPACK_SKIP_ROWS, y);
672
673                 glTexSubImage2D(GL_TEXTURE_2D, 0, x, y, w, h, GL_RGBA,
674                         GL_UNSIGNED_BYTE, ibuf->rect);
675
676                 glPixelStorei(GL_UNPACK_ROW_LENGTH, row_length);
677                 glPixelStorei(GL_UNPACK_SKIP_PIXELS, skip_pixels);
678                 glPixelStorei(GL_UNPACK_SKIP_ROWS, skip_rows);
679
680                 if(ima->tpageflag & IMA_MIPMAP_COMPLETE)
681                         ima->tpageflag &= ~IMA_MIPMAP_COMPLETE;
682         }
683 }
684
685 void GPU_update_images_framechange(void)
686 {
687         Image *ima;
688         
689         for(ima=G.main->image.first; ima; ima=ima->id.next) {
690                 if(ima->tpageflag & IMA_TWINANIM) {
691                         if(ima->twend >= ima->xrep*ima->yrep)
692                                 ima->twend= ima->xrep*ima->yrep-1;
693                 
694                         /* check: is bindcode not in the array? free. (to do) */
695                         
696                         ima->lastframe++;
697                         if(ima->lastframe > ima->twend)
698                                 ima->lastframe= ima->twsta;
699                 }
700         }
701 }
702
703 int GPU_update_image_time(Image *ima, double time)
704 {
705         int     inc = 0;
706         float   diff;
707         int     newframe;
708
709         if (!ima)
710                 return 0;
711
712         if (ima->lastupdate<0)
713                 ima->lastupdate = 0;
714
715         if (ima->lastupdate>time)
716                 ima->lastupdate=(float)time;
717
718         if(ima->tpageflag & IMA_TWINANIM) {
719                 if(ima->twend >= ima->xrep*ima->yrep) ima->twend= ima->xrep*ima->yrep-1;
720                 
721                 /* check: is the bindcode not in the array? Then free. (still to do) */
722                 
723                 diff = (float)(time-ima->lastupdate);
724                 inc = (int)(diff*(float)ima->animspeed);
725
726                 ima->lastupdate+=((float)inc/(float)ima->animspeed);
727
728                 newframe = ima->lastframe+inc;
729
730                 if(newframe > (int)ima->twend) {
731                         if(ima->twend-ima->twsta != 0)
732                                 newframe = (int)ima->twsta-1 + (newframe-ima->twend)%(ima->twend-ima->twsta);
733                         else
734                                 newframe = ima->twsta;
735                 }
736
737                 ima->lastframe = newframe;
738         }
739
740         return inc;
741 }
742
743 void GPU_free_image(Image *ima)
744 {
745         /* free regular image binding */
746         if(ima->bindcode) {
747                 glDeleteTextures(1, (GLuint *)&ima->bindcode);
748                 ima->bindcode= 0;
749                 ima->tpageflag &= ~IMA_MIPMAP_COMPLETE;
750         }
751
752         /* free glsl image binding */
753         if(ima->gputexture) {
754                 GPU_texture_free(ima->gputexture);
755                 ima->gputexture= NULL;
756         }
757
758         /* free repeated image binding */
759         if(ima->repbind) {
760                 glDeleteTextures(ima->totbind, (GLuint *)ima->repbind);
761         
762                 MEM_freeN(ima->repbind);
763                 ima->repbind= NULL;
764                 ima->tpageflag &= ~IMA_MIPMAP_COMPLETE;
765         }
766 }
767
768 void GPU_free_images(void)
769 {
770         Image* ima;
771
772         if(G.main)
773                 for(ima=G.main->image.first; ima; ima=ima->id.next)
774                         GPU_free_image(ima);
775 }
776
777 /* OpenGL Materials */
778
779 /* materials start counting at # one.... */
780 #define MAXMATBUF (MAXMAT+1)
781
782 /* OpenGL state caching for materials */
783
784 static struct GPUMaterialState {
785         float matbuf[MAXMATBUF][2][4];
786         int totmat;
787
788         Material *gmatbuf[MAXMATBUF];
789         Material *gboundmat;
790         Object *gob;
791         Scene *gscene;
792         int glay;
793         float (*gviewmat)[4];
794         float (*gviewinv)[4];
795
796         GPUBlendMode blendmode[MAXMATBUF];
797         int alphapass;
798
799         int lastmatnr, lastretval;
800         GPUBlendMode lastblendmode;
801 } GMS;
802
803 Material *gpu_active_node_material(Material *ma)
804 {
805         if(ma && ma->use_nodes && ma->nodetree) {
806                 bNode *node= nodeGetActiveID(ma->nodetree, ID_MA);
807
808                 if(node)
809                         return (Material *)node->id;
810                 else
811                         return NULL;
812         }
813
814         return ma;
815 }
816
817 void GPU_set_object_materials(View3D *v3d, RegionView3D *rv3d, Scene *scene, Object *ob, int glsl, int *do_alpha_pass)
818 {
819         extern Material defmaterial; /* from material.c */
820         Material *ma;
821         GPUMaterial *gpumat;
822         GPUBlendMode blendmode;
823         int a;
824         
825         /* initialize state */
826         memset(&GMS, 0, sizeof(GMS));
827         GMS.lastmatnr = -1;
828         GMS.lastretval = -1;
829         GMS.lastblendmode = GPU_BLEND_SOLID;
830
831         GMS.gob = ob;
832         GMS.gscene = scene;
833         GMS.totmat= ob->totcol;
834         GMS.glay= v3d->lay;
835         GMS.gviewmat= rv3d->viewmat;
836         GMS.gviewinv= rv3d->viewinv;
837
838         GMS.alphapass = (v3d && v3d->transp);
839         if(do_alpha_pass)
840                 *do_alpha_pass = 0;
841
842         /* no materials assigned? */
843         if(ob->totcol==0) {
844                 GMS.matbuf[0][0][0]= defmaterial.r;
845                 GMS.matbuf[0][0][1]= defmaterial.g;
846                 GMS.matbuf[0][0][2]= defmaterial.b;
847                 GMS.matbuf[0][0][3]= 1.0;
848
849                 GMS.matbuf[0][1][0]= defmaterial.specr;
850                 GMS.matbuf[0][1][1]= defmaterial.specg;
851                 GMS.matbuf[0][1][2]= defmaterial.specb;
852                 GMS.matbuf[0][1][3]= 1.0;
853                 
854                 /* do material 1 too, for displists! */
855                 QUATCOPY(GMS.matbuf[1][0], GMS.matbuf[0][0]);
856                 QUATCOPY(GMS.matbuf[1][1], GMS.matbuf[0][1]);
857
858                 if(glsl) {
859                         GMS.gmatbuf[0]= &defmaterial;
860                         GPU_material_from_blender(GMS.gscene, &defmaterial);
861                 }
862
863                 GMS.blendmode[0]= GPU_BLEND_SOLID;
864         }
865         
866         /* setup materials */
867         for(a=1; a<=ob->totcol; a++) {
868                 /* find a suitable material */
869                 ma= give_current_material(ob, a);
870                 if(!glsl) ma= gpu_active_node_material(ma);
871                 if(ma==NULL) ma= &defmaterial;
872
873                 /* this shouldn't happen .. */
874                 if(a>=MAXMATBUF)
875                         continue;
876
877                 /* create glsl material if requested */
878                 gpumat = (glsl)? GPU_material_from_blender(GMS.gscene, ma): NULL;
879
880                 if(gpumat) {
881                         /* do glsl only if creating it succeed, else fallback */
882                         GMS.gmatbuf[a]= ma;
883                         blendmode = GPU_material_blend_mode(gpumat, ob->col);
884                 }
885                 else {
886                         /* fixed function opengl materials */
887                         if (ma->mode & MA_SHLESS) {
888                                 GMS.matbuf[a][0][0]= ma->r;
889                                 GMS.matbuf[a][0][1]= ma->g;
890                                 GMS.matbuf[a][0][2]= ma->b;
891                         } else {
892                                 GMS.matbuf[a][0][0]= (ma->ref+ma->emit)*ma->r;
893                                 GMS.matbuf[a][0][1]= (ma->ref+ma->emit)*ma->g;
894                                 GMS.matbuf[a][0][2]= (ma->ref+ma->emit)*ma->b;
895
896                                 GMS.matbuf[a][1][0]= ma->spec*ma->specr;
897                                 GMS.matbuf[a][1][1]= ma->spec*ma->specg;
898                                 GMS.matbuf[a][1][2]= ma->spec*ma->specb;
899                                 GMS.matbuf[a][1][3]= 1.0;
900                         }
901
902                         blendmode = (ma->alpha == 1.0f)? GPU_BLEND_SOLID: GPU_BLEND_ALPHA;
903                         if(do_alpha_pass && GMS.alphapass)
904                                 GMS.matbuf[a][0][3]= ma->alpha;
905                         else
906                                 GMS.matbuf[a][0][3]= 1.0f;
907                 }
908
909                 /* setting do_alpha_pass = 1 indicates this object needs to be
910                  * drawn in a second alpha pass for improved blending */
911                 if(do_alpha_pass) {
912                         GMS.blendmode[a]= blendmode;
913                         if(ELEM(blendmode, GPU_BLEND_ALPHA, GPU_BLEND_ADD) && !GMS.alphapass)
914                                 *do_alpha_pass= 1;
915                 }
916         }
917
918         /* let's start with a clean state */
919         GPU_disable_material();
920 }
921
922 int GPU_enable_material(int nr, void *attribs)
923 {
924         GPUVertexAttribs *gattribs = attribs;
925         GPUMaterial *gpumat;
926         GPUBlendMode blendmode;
927
928         /* prevent index to use un-initialized array items */
929         if(nr>GMS.totmat)
930                 nr= GMS.totmat;
931
932         if(gattribs)
933                 memset(gattribs, 0, sizeof(*gattribs));
934
935         /* keep current material */
936         if(nr>=MAXMATBUF || nr==GMS.lastmatnr)
937                 return GMS.lastretval;
938
939         /* unbind glsl material */
940         if(GMS.gboundmat) {
941                 if(GMS.alphapass) glDepthMask(0);
942                 GPU_material_unbind(GPU_material_from_blender(GMS.gscene, GMS.gboundmat));
943                 GMS.gboundmat= NULL;
944         }
945
946         /* draw materials with alpha in alpha pass */
947         GMS.lastmatnr = nr;
948         GMS.lastretval = ELEM(GMS.blendmode[nr], GPU_BLEND_SOLID, GPU_BLEND_CLIP);
949         if(GMS.alphapass)
950                 GMS.lastretval = !GMS.lastretval;
951
952         if(GMS.lastretval) {
953                 if(gattribs && GMS.gmatbuf[nr]) {
954                         /* bind glsl material and get attributes */
955                         Material *mat = GMS.gmatbuf[nr];
956
957                         gpumat = GPU_material_from_blender(GMS.gscene, mat);
958                         GPU_material_vertex_attributes(gpumat, gattribs);
959                         GPU_material_bind(gpumat, GMS.gob->lay, GMS.glay, 1.0);
960                         GPU_material_bind_uniforms(gpumat, GMS.gob->obmat, GMS.gviewmat, GMS.gviewinv, GMS.gob->col);
961                         GMS.gboundmat= mat;
962
963                         if(GMS.alphapass) glDepthMask(1);
964                 }
965                 else {
966                         /* or do fixed function opengl material */
967                         glMaterialfv(GL_FRONT_AND_BACK, GL_DIFFUSE, GMS.matbuf[nr][0]);
968                         glMaterialfv(GL_FRONT_AND_BACK, GL_SPECULAR, GMS.matbuf[nr][1]);
969                 }
970
971                 /* set (alpha) blending mode */
972                 blendmode = (GMS.alphapass)? GPU_BLEND_ALPHA: GPU_BLEND_SOLID;
973                 GPU_set_material_blend_mode(blendmode);
974         }
975
976         return GMS.lastretval;
977 }
978
979 void GPU_set_material_blend_mode(int blendmode)
980 {
981         if(GMS.lastblendmode == blendmode)
982                 return;
983         
984         gpu_set_blend_mode(blendmode);
985         GMS.lastblendmode = blendmode;
986 }
987
988 int GPU_get_material_blend_mode(void)
989 {
990         return GMS.lastblendmode;
991 }
992
993 void GPU_disable_material(void)
994 {
995         GMS.lastmatnr= -1;
996         GMS.lastretval= 1;
997
998         if(GMS.gboundmat) {
999                 if(GMS.alphapass) glDepthMask(0);
1000                 GPU_material_unbind(GPU_material_from_blender(GMS.gscene, GMS.gboundmat));
1001                 GMS.gboundmat= NULL;
1002         }
1003
1004         GPU_set_material_blend_mode(GPU_BLEND_SOLID);
1005 }
1006
1007 /* Lights */
1008
1009 int GPU_default_lights(void)
1010 {
1011         int a, count = 0;
1012         
1013         /* initialize */
1014         if(U.light[0].flag==0 && U.light[1].flag==0 && U.light[2].flag==0) {
1015                 U.light[0].flag= 1;
1016                 U.light[0].vec[0]= -0.3; U.light[0].vec[1]= 0.3; U.light[0].vec[2]= 0.9;
1017                 U.light[0].col[0]= 0.8; U.light[0].col[1]= 0.8; U.light[0].col[2]= 0.8;
1018                 U.light[0].spec[0]= 0.5; U.light[0].spec[1]= 0.5; U.light[0].spec[2]= 0.5;
1019                 U.light[0].spec[3]= 1.0;
1020                 
1021                 U.light[1].flag= 0;
1022                 U.light[1].vec[0]= 0.5; U.light[1].vec[1]= 0.5; U.light[1].vec[2]= 0.1;
1023                 U.light[1].col[0]= 0.4; U.light[1].col[1]= 0.4; U.light[1].col[2]= 0.8;
1024                 U.light[1].spec[0]= 0.3; U.light[1].spec[1]= 0.3; U.light[1].spec[2]= 0.5;
1025                 U.light[1].spec[3]= 1.0;
1026         
1027                 U.light[2].flag= 0;
1028                 U.light[2].vec[0]= 0.3; U.light[2].vec[1]= -0.3; U.light[2].vec[2]= -0.2;
1029                 U.light[2].col[0]= 0.8; U.light[2].col[1]= 0.5; U.light[2].col[2]= 0.4;
1030                 U.light[2].spec[0]= 0.5; U.light[2].spec[1]= 0.4; U.light[2].spec[2]= 0.3;
1031                 U.light[2].spec[3]= 1.0;
1032         }
1033
1034         glLightModeli(GL_LIGHT_MODEL_LOCAL_VIEWER, GL_FALSE);
1035
1036         glLightfv(GL_LIGHT0, GL_POSITION, U.light[0].vec); 
1037         glLightfv(GL_LIGHT0, GL_DIFFUSE, U.light[0].col); 
1038         glLightfv(GL_LIGHT0, GL_SPECULAR, U.light[0].spec); 
1039
1040         glLightfv(GL_LIGHT1, GL_POSITION, U.light[1].vec); 
1041         glLightfv(GL_LIGHT1, GL_DIFFUSE, U.light[1].col); 
1042         glLightfv(GL_LIGHT1, GL_SPECULAR, U.light[1].spec); 
1043
1044         glLightfv(GL_LIGHT2, GL_POSITION, U.light[2].vec); 
1045         glLightfv(GL_LIGHT2, GL_DIFFUSE, U.light[2].col); 
1046         glLightfv(GL_LIGHT2, GL_SPECULAR, U.light[2].spec); 
1047
1048         for(a=0; a<8; a++) {
1049                 if(a<3) {
1050                         if(U.light[a].flag) {
1051                                 glEnable(GL_LIGHT0+a);
1052                                 count++;
1053                         }
1054                         else
1055                                 glDisable(GL_LIGHT0+a);
1056                         
1057                         // clear stuff from other opengl lamp usage
1058                         glLightf(GL_LIGHT0+a, GL_SPOT_CUTOFF, 180.0);
1059                         glLightf(GL_LIGHT0+a, GL_CONSTANT_ATTENUATION, 1.0);
1060                         glLightf(GL_LIGHT0+a, GL_LINEAR_ATTENUATION, 0.0);
1061                 }
1062                 else
1063                         glDisable(GL_LIGHT0+a);
1064         }
1065         
1066         glDisable(GL_LIGHTING);
1067
1068         glDisable(GL_COLOR_MATERIAL);
1069
1070         return count;
1071 }
1072
1073 int GPU_scene_object_lights(Scene *scene, Object *ob, int lay, float viewmat[][4], int ortho)
1074 {
1075         Base *base;
1076         Lamp *la;
1077         int count;
1078         float position[4], direction[4], energy[4];
1079         
1080         /* disable all lights */
1081         for(count=0; count<8; count++)
1082                 glDisable(GL_LIGHT0+count);
1083         
1084         /* view direction for specular is not compute correct by default in
1085          * opengl, so we set the settings ourselfs */
1086         glLightModeli(GL_LIGHT_MODEL_LOCAL_VIEWER, (ortho)? GL_FALSE: GL_TRUE);
1087
1088         count= 0;
1089         
1090         for(base=scene->base.first; base; base=base->next) {
1091                 if(base->object->type!=OB_LAMP)
1092                         continue;
1093
1094                 if(!(base->lay & lay) || !(base->lay & ob->lay))
1095                         continue;
1096
1097                 la= base->object->data;
1098                 
1099                 /* setup lamp transform */
1100                 glPushMatrix();
1101                 glLoadMatrixf((float *)viewmat);
1102                 
1103                 where_is_object_simul(scene, base->object);
1104                 
1105                 if(la->type==LA_SUN) {
1106                         /* sun lamp */
1107                         VECCOPY(direction, base->object->obmat[2]);
1108                         direction[3]= 0.0;
1109
1110                         glLightfv(GL_LIGHT0+count, GL_POSITION, direction); 
1111                 }
1112                 else {
1113                         /* other lamps with attenuation */
1114                         VECCOPY(position, base->object->obmat[3]);
1115                         position[3]= 1.0f;
1116
1117                         glLightfv(GL_LIGHT0+count, GL_POSITION, position); 
1118                         glLightf(GL_LIGHT0+count, GL_CONSTANT_ATTENUATION, 1.0);
1119                         glLightf(GL_LIGHT0+count, GL_LINEAR_ATTENUATION, la->att1/la->dist);
1120                         glLightf(GL_LIGHT0+count, GL_QUADRATIC_ATTENUATION, la->att2/(la->dist*la->dist));
1121                         
1122                         if(la->type==LA_SPOT) {
1123                                 /* spot lamp */
1124                                 direction[0]= -base->object->obmat[2][0];
1125                                 direction[1]= -base->object->obmat[2][1];
1126                                 direction[2]= -base->object->obmat[2][2];
1127                                 glLightfv(GL_LIGHT0+count, GL_SPOT_DIRECTION, direction);
1128                                 glLightf(GL_LIGHT0+count, GL_SPOT_CUTOFF, la->spotsize/2.0);
1129                                 glLightf(GL_LIGHT0+count, GL_SPOT_EXPONENT, 128.0*la->spotblend);
1130                         }
1131                         else
1132                                 glLightf(GL_LIGHT0+count, GL_SPOT_CUTOFF, 180.0);
1133                 }
1134                 
1135                 /* setup energy */
1136                 energy[0]= la->energy*la->r;
1137                 energy[1]= la->energy*la->g;
1138                 energy[2]= la->energy*la->b;
1139                 energy[3]= 1.0;
1140
1141                 glLightfv(GL_LIGHT0+count, GL_DIFFUSE, energy); 
1142                 glLightfv(GL_LIGHT0+count, GL_SPECULAR, energy);
1143                 glEnable(GL_LIGHT0+count);
1144                 
1145                 glPopMatrix();                                  
1146                 
1147                 count++;
1148                 if(count==8)
1149                         break;
1150         }
1151
1152         return count;
1153 }
1154
1155 /* Default OpenGL State */
1156
1157 void GPU_state_init(void)
1158 {
1159         /* also called when doing opengl rendering and in the game engine */
1160         float mat_ambient[] = { 0.0, 0.0, 0.0, 0.0 };
1161         float mat_specular[] = { 0.5, 0.5, 0.5, 1.0 };
1162         float mat_shininess[] = { 35.0 };
1163         int a, x, y;
1164         GLubyte pat[32*32];
1165         const GLubyte *patc= pat;
1166         
1167         glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT, mat_ambient);
1168         glMaterialfv(GL_FRONT_AND_BACK, GL_DIFFUSE, mat_specular);
1169         glMaterialfv(GL_FRONT_AND_BACK, GL_SPECULAR, mat_specular);
1170         glMaterialfv(GL_FRONT_AND_BACK, GL_SHININESS, mat_shininess);
1171
1172         GPU_default_lights();
1173         
1174         glDepthFunc(GL_LEQUAL);
1175         /* scaling matrices */
1176         glEnable(GL_NORMALIZE);
1177
1178         glShadeModel(GL_FLAT);
1179
1180         glDisable(GL_ALPHA_TEST);
1181         glDisable(GL_BLEND);
1182         glDisable(GL_DEPTH_TEST);
1183         glDisable(GL_FOG);
1184         glDisable(GL_LIGHTING);
1185         glDisable(GL_LOGIC_OP);
1186         glDisable(GL_STENCIL_TEST);
1187         glDisable(GL_TEXTURE_1D);
1188         glDisable(GL_TEXTURE_2D);
1189
1190         /* default on, disable/enable should be local per function */
1191         glEnableClientState(GL_VERTEX_ARRAY);
1192         glEnableClientState(GL_NORMAL_ARRAY);
1193         
1194         glPixelTransferi(GL_MAP_COLOR, GL_FALSE);
1195         glPixelTransferi(GL_RED_SCALE, 1);
1196         glPixelTransferi(GL_RED_BIAS, 0);
1197         glPixelTransferi(GL_GREEN_SCALE, 1);
1198         glPixelTransferi(GL_GREEN_BIAS, 0);
1199         glPixelTransferi(GL_BLUE_SCALE, 1);
1200         glPixelTransferi(GL_BLUE_BIAS, 0);
1201         glPixelTransferi(GL_ALPHA_SCALE, 1);
1202         glPixelTransferi(GL_ALPHA_BIAS, 0);
1203         
1204         glPixelTransferi(GL_DEPTH_BIAS, 0);
1205         glPixelTransferi(GL_DEPTH_SCALE, 1);
1206         glDepthRange(0.0, 1.0);
1207         
1208         a= 0;
1209         for(x=0; x<32; x++) {
1210                 for(y=0; y<4; y++) {
1211                         if( (x) & 1) pat[a++]= 0x88;
1212                         else pat[a++]= 0x22;
1213                 }
1214         }
1215         
1216         glPolygonStipple(patc);
1217
1218         glMatrixMode(GL_TEXTURE);
1219         glLoadIdentity();
1220         glMatrixMode(GL_MODELVIEW);
1221
1222         glFrontFace(GL_CCW);
1223         glCullFace(GL_BACK);
1224         glDisable(GL_CULL_FACE);
1225 }
1226