]> icculus.org git repositories - taylor/freespace2.git/blob - src/graphics/gropengl.cpp
various valgrind warning fixes
[taylor/freespace2.git] / src / graphics / gropengl.cpp
1 /*
2  * Copyright (C) Volition, Inc. 1999.  All rights reserved.
3  *
4  * All source code herein is the property of Volition, Inc. You may not sell 
5  * or otherwise commercially exploit the source or things you created based on
6  * the source.
7  */
8
9 /*
10  * $Logfile: /Freespace2/code/Graphics/GrOpenGL.cpp $
11  * $Revision$
12  * $Date$
13  * $Author$
14  *
15  * Code that uses the OpenGL graphics library
16  *
17  * $Log$
18  * Revision 1.76  2005/10/01 21:44:43  taylor
19  * slight speedup to font rendering by not doing something that should be global for each letter
20  * little cleanup to better deal with FS2_Open related changes
21  * don't deal with the extra texmem stuff if we don't have to, saves on temporary memory usage and speed
22  *
23  * Revision 1.75  2005/08/12 20:24:31  taylor
24  * some OSX GCC4 fixin (LEgregius)
25  *
26  * Revision 1.74  2005/08/12 08:57:20  taylor
27  * don't show hardware S-RAM value on HUD in debug
28  * do show in use GL texture memory
29  * have an actual fade effect for the credits screen artwork
30  *
31  * Revision 1.73  2005/04/02 18:58:08  taylor
32  * attempt to fix garbage at end of GL extension string
33  *
34  * Revision 1.72  2005/03/30 01:20:12  taylor
35  * Screenshot function filled, will output into ~/.freespace(2)/Data
36  * Use glTexSubImage2D on reloaded texture slots, this is only used by ANIs
37  *
38  * Revision 1.71  2004/12/15 04:10:45  taylor
39  * outwnd_unix.cpp from fs2_open for logging to file in debug mode
40  * fixes for default function values
41  * always use vm_* functions for sanity sake
42  * make cfilearchiver 64-bit compatible
43  * fix crash on exit from double free()
44  * fix crash on startup from extra long GL extension string in debug
45  *
46  * Revision 1.70  2004/09/20 01:31:44  theoddone33
47  * GCC 3.4 fixes.
48  *
49  * Revision 1.69  2004/07/04 11:31:43  taylor
50  * amd64 support, compiler warning fixes, don't use software rendering
51  *
52  * Revision 1.68  2004/06/11 01:01:07  tigital
53  * added FSAA support: switched on in .ini
54  *
55  * Revision 1.67  2003/08/03 15:59:40  taylor
56  * GL_RGB5_A1 as TexImage internal format; cleaner input grab; min window title; cleanup
57  *
58  * Revision 1.66  2003/06/22 12:52:34  taylor
59  * more texture size fixin
60  *
61  * Revision 1.65  2003/06/19 11:52:47  taylor
62  * fix texture size issue with lower detail settings
63  *
64  * Revision 1.64  2003/05/28 06:02:04  taylor
65  * fix transparency in green weapon blobs
66  *
67  * Revision 1.63  2003/05/09 05:05:52  taylor
68  * improve gr_(de)activate, mouse grab, default fullscreen
69  *
70  * Revision 1.62  2003/05/04 04:56:53  taylor
71  * move SDL_Quit to os_deinit to fix fonttool segfault
72  *
73  * Revision 1.61  2003/02/02 21:13:27  relnev
74  * minor updates (made functions static, tried to improve texture sizes)
75  *
76  * Revision 1.60  2003/02/02 20:20:03  relnev
77  * add large texture support (Taylor Richards)
78  *
79  * Revision 1.59  2002/09/04 01:38:09  relnev
80  * revert
81  *
82  * Revision 1.57  2002/08/31 01:39:13  theoddone33
83  * Speed up the renderer a tad
84  *
85  * Revision 1.56  2002/08/01 05:03:11  relnev
86  * minor change
87  *
88  * Revision 1.55  2002/08/01 04:55:45  relnev
89  * experimenting with texture state
90  *
91  * Revision 1.54  2002/07/30 15:00:15  relnev
92  * not use luminance alpha by default
93  *
94  * Revision 1.53  2002/06/22 17:08:16  relnev
95  * more fixes to unused alpha code
96  *
97  * Revision 1.52  2002/06/21 23:59:14  relnev
98  * moved a gr_opengl_set_state to after the gr_tcache_set
99  *
100  * Revision 1.51  2002/06/19 04:52:45  relnev
101  * MacOS X updates (Ryan)
102  *
103  * Revision 1.50  2002/06/18 23:20:44  relnev
104  * fixed _splitpath.
105  *
106  * adjusted line offsets.
107  *
108  * Revision 1.49  2002/06/17 23:11:39  relnev
109  * enable sdl key repeating.
110  *
111  * swap '/` keys.
112  *
113  * Revision 1.48  2002/06/09 04:41:17  relnev
114  * added copyright header
115  *
116  * Revision 1.47  2002/06/09 03:16:04  relnev
117  * added _splitpath.
118  *
119  * removed unneeded asm, old sdl 2d setup.
120  *
121  * fixed crash caused by opengl_get_region.
122  *
123  * Revision 1.46  2002/06/05 04:03:32  relnev
124  * finished cfilesystem.
125  *
126  * removed some old code.
127  *
128  * fixed mouse save off-by-one.
129  *
130  * sound cleanups.
131  *
132  * Revision 1.45  2002/06/03 09:25:37  relnev
133  * implement mouse cursor and screen save/restore
134  *
135  * Revision 1.44  2002/06/02 18:46:59  relnev
136  * updated
137  *
138  * Revision 1.43  2002/06/02 11:34:00  relnev
139  * adjust z coords
140  *
141  * Revision 1.42  2002/06/02 10:28:17  relnev
142  * fix texture handle leak
143  *
144  * Revision 1.41  2002/06/01 09:00:34  relnev
145  * silly debug memmanager
146  *
147  * Revision 1.40  2002/06/01 07:12:33  relnev
148  * a few NDEBUG updates.
149  *
150  * removed a few warnings.
151  *
152  * Revision 1.39  2002/06/01 05:33:15  relnev
153  * copied more code over.
154  *
155  * added scissor clipping.
156  *
157  * Revision 1.38  2002/06/01 03:35:27  relnev
158  * fix typo
159  *
160  * Revision 1.37  2002/06/01 03:32:00  relnev
161  * fix texture loading mistake.
162  *
163  * enable some d3d stuff for opengl also
164  *
165  * Revision 1.36  2002/05/31 23:25:03  relnev
166  * line fixes
167  *
168  * Revision 1.34  2002/05/31 22:15:22  relnev
169  * BGRA
170  *
171  * Revision 1.33  2002/05/31 22:04:55  relnev
172  * use d3d rect_internal
173  *
174  * Revision 1.32  2002/05/31 06:28:23  relnev
175  * more stuff
176  *
177  * Revision 1.31  2002/05/31 06:04:39  relnev
178  * fog
179  *
180  * Revision 1.30  2002/05/31 03:56:11  theoddone33
181  * Change tmapper polygon winding and enable culling
182  *
183  * Revision 1.29  2002/05/31 03:34:02  theoddone33
184  * Fix Keyboard
185  * Add titlebar
186  *
187  * Revision 1.28  2002/05/31 00:06:59  relnev
188  * minor change
189  *
190  * Revision 1.27  2002/05/30 23:46:29  theoddone33
191  * some minor key changes (not necessarily fixes)
192  *
193  * Revision 1.26  2002/05/30 23:33:12  relnev
194  * implemented a few more functions.
195  *
196  * Revision 1.25  2002/05/30 23:01:16  relnev
197  * implement gr_opengl_set_state.
198  *
199  * Revision 1.24  2002/05/30 22:12:57  relnev
200  * finish default texture case
201  *
202  * Revision 1.23  2002/05/30 22:02:30  theoddone33
203  * More gl changes
204  *
205  * Revision 1.22  2002/05/30 21:44:48  relnev
206  * implemented some missing texture stuff.
207  *
208  * enable bitmap polys for opengl.
209  *
210  * work around greenness in bitmaps.
211  *
212  * Revision 1.21  2002/05/30 17:29:30  theoddone33
213  * Fix some more stubs, change at least one polygon winding since culling is now
214  * enabled.
215  *
216  * Revision 1.20  2002/05/30 16:50:24  theoddone33
217  * Keyboard partially fixed
218  *
219  * Revision 1.19  2002/05/30 08:13:14  relnev
220  * fonts are fixed
221  *
222  * Revision 1.18  2002/05/29 23:37:36  relnev
223  * fix bitmap bug
224  *
225  * Revision 1.17  2002/05/29 23:17:49  theoddone33
226  * Non working text code and fixed keys
227  *
228  * Revision 1.16  2002/05/29 19:45:13  theoddone33
229  * More changes on texture loading
230  *
231  * Revision 1.15  2002/05/29 19:06:48  theoddone33
232  * Enable string printing.  Enable texture mapping
233  *
234  * Revision 1.14  2002/05/29 08:54:40  relnev
235  * "fixed" bitmap drawing.
236  *
237  * copied more d3d code over.
238  *
239  * Revision 1.13  2002/05/29 06:25:13  theoddone33
240  * Keyboard input, mouse tracking now work
241  *
242  * Revision 1.12  2002/05/29 04:52:45  relnev
243  * bitmap
244  *
245  * Revision 1.11  2002/05/29 04:29:56  relnev
246  * removed some unncessary stubbing, implemented opengl rect
247  *
248  * Revision 1.10  2002/05/29 04:13:27  theoddone33
249  * enable opengl_line
250  *
251  * Revision 1.9  2002/05/29 03:35:51  relnev
252  * added rest of init
253  *
254  * Revision 1.8  2002/05/29 03:30:05  relnev
255  * update opengl stubs
256  *
257  * Revision 1.7  2002/05/29 02:52:32  theoddone33
258  * Enable OpenGL renderer
259  *
260  * Revision 1.6  2002/05/28 04:56:51  theoddone33
261  * runs a little bit now
262  *
263  * Revision 1.5  2002/05/28 04:07:28  theoddone33
264  * New graphics stubbing arrangement
265  *
266  * Revision 1.4  2002/05/27 23:39:34  relnev
267  * 0
268  *
269  * Revision 1.3  2002/05/27 22:35:01  theoddone33
270  * more symbols
271  *
272  * Revision 1.2  2002/05/27 22:32:02  theoddone33
273  * throw all d3d stuff at opengl
274  *
275  * Revision 1.1.1.1  2002/05/03 03:28:09  root
276  * Initial import.
277  *
278  * 
279  * 10    7/14/99 9:42a Dave
280  * Put in clear_color debug function. Put in base for 3dnow stuff / P3
281  * stuff
282  * 
283  * 9     7/09/99 9:51a Dave
284  * Added thick polyline code.
285  * 
286  * 8     6/29/99 10:35a Dave
287  * Interface polygon bitmaps! Whee!
288  * 
289  * 7     2/03/99 11:44a Dave
290  * Fixed d3d transparent textures.
291  * 
292  * 6     1/24/99 11:37p Dave
293  * First full rev of beam weapons. Very customizable. Removed some bogus
294  * Int3()'s in low level net code.
295  * 
296  * 5     12/18/98 1:13a Dave
297  * Rough 1024x768 support for Direct3D. Proper detection and usage through
298  * the launcher.
299  * 
300  * 4     12/06/98 2:36p Dave
301  * Drastically improved nebula fogging.
302  * 
303  * 3     11/11/98 5:37p Dave
304  * Checkin for multiplayer testing.
305  * 
306  * 2     10/07/98 10:53a Dave
307  * Initial checkin.
308  * 
309  * 1     10/07/98 10:49a Dave
310  * 
311  * 14    5/20/98 9:46p John
312  * added code so the places in code that change half the palette don't
313  * have to clear the screen.
314  * 
315  * 13    5/06/98 5:30p John
316  * Removed unused cfilearchiver.  Removed/replaced some unused/little used
317  * graphics functions, namely gradient_h and _v and pixel_sp.   Put in new
318  * DirectX header files and libs that fixed the Direct3D alpha blending
319  * problems.
320  * 
321  * 12    4/14/98 12:15p John
322  * Made 16-bpp movies work.
323  * 
324  * 11    3/12/98 5:36p John
325  * Took out any unused shaders.  Made shader code take rgbc instead of
326  * matrix and vector since noone used it like a matrix and it would have
327  * been impossible to do in hardware.   Made Glide implement a basic
328  * shader for online help.  
329  * 
330  * 10    3/10/98 4:18p John
331  * Cleaned up graphics lib.  Took out most unused gr functions.   Made D3D
332  * & Glide have popups and print screen.  Took out all >8bpp software
333  * support.  Made Fred zbuffer.  Made zbuffer allocate dynamically to
334  * support Fred.  Made zbuffering key off of functions rather than one
335  * global variable.
336  * 
337  * 9     12/02/97 4:00p John
338  * Added first rev of thruster glow, along with variable levels of
339  * translucency, which retquired some restructing of palman.
340  * 
341  * 8     10/03/97 9:10a John
342  * added better antialiased line drawer
343  * 
344  * 7     9/23/97 10:45a John
345  * made so you can tell bitblt code to rle a bitmap by passing flag to
346  * gr_set_bitmap
347  * 
348  * 6     9/09/97 11:01a Sandeep
349  * fixed warning level 4 bugs
350  * 
351  * 5     7/10/97 2:06p John
352  * added code to specify alphablending type for bitmaps.
353  * 
354  * 4     6/17/97 7:04p John
355  * added d3d support for gradients.
356  * fixed some color bugs by adding screen signatures instead of watching
357  * flags and palette changes.
358  * 
359  * 3     6/12/97 2:50a Lawrance
360  * bm_unlock() now passed bitmap number, not pointer
361  * 
362  * 2     6/11/97 1:12p John
363  * Started fixing all the text colors in the game.
364  * 
365  * 1     5/12/97 12:14p John
366  *
367  * $NoKeywords: $
368  */
369
370 #ifndef PLAT_UNIX
371 #include <windows.h>
372 #include <windowsx.h>
373 #endif
374
375 #include "pstypes.h"
376 #include "osapi.h"
377 #include "2d.h"
378 #include "3d.h"
379 #include "bmpman.h"
380 #include "floating.h"
381 #include "palman.h"
382 #include "systemvars.h"
383 #include "grinternal.h"
384 #include "gropengl.h"
385 #include "line.h"
386 #include "neb.h"
387 #include "mouse.h"
388 #include "osregistry.h"
389 #include "cmdline.h"
390 #include "cfile.h"
391
392 static int Inited = 0;
393
394 typedef enum gr_texture_source {
395         TEXTURE_SOURCE_NONE,
396         TEXTURE_SOURCE_DECAL,
397         TEXTURE_SOURCE_NO_FILTERING,
398 } gr_texture_source;
399
400 typedef enum gr_alpha_blend {
401         ALPHA_BLEND_NONE,                       // 1*SrcPixel + 0*DestPixel
402         ALPHA_BLEND_ADDITIVE,                   // 1*SrcPixel + 1*DestPixel
403         ALPHA_BLEND_ALPHA_ADDITIVE,             // Alpha*SrcPixel + 1*DestPixel
404         ALPHA_BLEND_ALPHA_BLEND_ALPHA,          // Alpha*SrcPixel + (1-Alpha)*DestPixel
405         ALPHA_BLEND_ALPHA_BLEND_SRC_COLOR,      // Alpha*SrcPixel + (1-SrcPixel)*DestPixel
406 } gr_alpha_blend;
407
408 typedef enum gr_zbuffer_type {
409         ZBUFFER_TYPE_NONE,
410         ZBUFFER_TYPE_READ,
411         ZBUFFER_TYPE_WRITE,
412         ZBUFFER_TYPE_FULL,
413 } gr_zbuffer_type;
414                         
415 #define NEBULA_COLORS 20
416
417 volatile int GL_activate = 0;
418 volatile int GL_deactivate = 0;
419
420 static int GL_use_luminance_alpha;
421 static int FSAA;
422 static ubyte GL_xlat[256] = { 0 };
423
424 static char *Gr_saved_screen = NULL;
425 static int Gr_saved_screen_bitmap;
426
427 static int Gr_opengl_mouse_saved = 0;
428 static int Gr_opengl_mouse_saved_x1 = 0;
429 static int Gr_opengl_mouse_saved_y1 = 0;
430 static int Gr_opengl_mouse_saved_x2 = 0;
431 static int Gr_opengl_mouse_saved_y2 = 0;
432 static int Gr_opengl_mouse_saved_w = 0;
433 static int Gr_opengl_mouse_saved_h = 0;
434 #define MAX_SAVE_SIZE (32*32)
435 static ubyte Gr_opengl_mouse_saved_data[MAX_SAVE_SIZE*2];
436
437 #define CLAMP(x,r1,r2) do { if ( (x) < (r1) ) (x) = (r1); else if ((x) > (r2)) (x) = (r2); } while(0)
438
439 #ifdef PLAT_UNIX
440 // Throw in some dummy functions - DDOI
441
442 int D3D_32bit = 0;              // grd3d.cpp
443 int D3D_fog_mode = -1;          // grd3d.cpp
444 int D3D_inited = 0;             // grd3d.cpp
445 int D3D_zbias = 1;              // grd3d.cpp
446 int D3d_rendition_uvs = 0;      // grd3d.cpp
447
448 void d3d_flush ()
449 {
450         STUB_FUNCTION;
451 }
452
453 void d3d_zbias (int a)
454 {
455         STUB_FUNCTION;
456 }
457 #endif
458
459 static void gr_opengl_set_texture_state(gr_texture_source ts);
460
461 static gr_alpha_blend GL_current_alpha_blend = (gr_alpha_blend) -1;
462 static gr_zbuffer_type GL_current_zbuffer_type = (gr_zbuffer_type) -1;
463
464 static void gr_opengl_set_state(gr_texture_source ts, gr_alpha_blend ab, gr_zbuffer_type zt)
465 {
466         gr_opengl_set_texture_state(ts);
467         
468         if (ab != GL_current_alpha_blend) {
469                 switch (ab) {
470                         case ALPHA_BLEND_NONE:                  // 1*SrcPixel + 0*DestPixel
471                                 glBlendFunc(GL_ONE, GL_ZERO);
472                                 break;
473                         case ALPHA_BLEND_ADDITIVE:              // 1*SrcPixel + 1*DestPixel
474                                 glBlendFunc(GL_ONE, GL_ONE);
475                                 break;
476                         case ALPHA_BLEND_ALPHA_ADDITIVE:        // Alpha*SrcPixel + 1*DestPixel
477                                 glBlendFunc(GL_SRC_ALPHA, GL_ONE);
478                                 break;
479                         case ALPHA_BLEND_ALPHA_BLEND_ALPHA:     // Alpha*SrcPixel + (1-Alpha)*DestPixel
480                                 glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
481                                 break;
482                         case ALPHA_BLEND_ALPHA_BLEND_SRC_COLOR: // Alpha*SrcPixel + (1-SrcPixel)*DestPixel
483                                 glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_COLOR);
484                                 break;
485                         default:
486                                 break;
487                 }
488                 
489                 GL_current_alpha_blend = ab;
490         }
491         
492         if (zt != GL_current_zbuffer_type) {
493                 switch (zt) {
494                         case ZBUFFER_TYPE_NONE:
495                                 glDepthFunc(GL_ALWAYS);
496                                 glDepthMask(GL_FALSE);
497                                 break;
498                         case ZBUFFER_TYPE_READ:
499                                 glDepthFunc(GL_LESS);
500                                 glDepthMask(GL_FALSE);  
501                                 break;
502                         case ZBUFFER_TYPE_WRITE:
503                                 glDepthFunc(GL_ALWAYS);
504                                 glDepthMask(GL_TRUE);
505                                 break;
506                         case ZBUFFER_TYPE_FULL:
507                                 glDepthFunc(GL_LESS);
508                                 glDepthMask(GL_TRUE);
509                                 break;
510                         default:
511                                 break;
512                 }
513                 
514                 GL_current_zbuffer_type = zt;
515         }       
516 }
517
518 void gr_opengl_activate(int active)
519 {
520         if (active) {
521                 GL_activate++;
522                 
523                 // don't grab key/mouse if cmdline says so or if we're fullscreen
524                 if(!Cmdline_no_grab && !(SDL_GetVideoSurface()->flags & SDL_FULLSCREEN)) {
525                         SDL_WM_GrabInput(SDL_GRAB_ON);
526                 }
527         } else {
528                 GL_deactivate++;
529                 
530                 // let go of mouse/keyboard
531                 SDL_WM_GrabInput(SDL_GRAB_OFF);
532         }
533 }
534
535
536 static void opengl_tcache_flush ();
537
538 void gr_opengl_preload_init()
539 {
540         if (gr_screen.mode != GR_OPENGL) {
541                 return;
542         }
543
544         opengl_tcache_flush ();
545 }
546
547 int GL_should_preload = 0;
548 int gr_opengl_preload(int bitmap_num, int is_aabitmap)
549 {
550         if ( gr_screen.mode != GR_OPENGL) {
551                 return 0;
552         }
553
554         if ( !GL_should_preload )      {
555                 return 0;
556         }
557
558         float u_scale, v_scale;
559
560         int retval;
561         if ( is_aabitmap )      {
562                 retval = gr_tcache_set(bitmap_num, TCACHE_TYPE_AABITMAP, &u_scale, &v_scale, 1, -1, -1, 0 );
563         } else {
564                 retval = gr_tcache_set(bitmap_num, TCACHE_TYPE_NORMAL, &u_scale, &v_scale, 1, -1, -1, 0 );
565         }
566
567         if ( !retval )  {
568                 mprintf(("Texture upload failed!\n" ));
569         }
570
571         return retval;
572 }
573
574 void gr_opengl_pixel(int x, int y)
575 {
576         gr_line(x,y,x,y);
577 }
578
579 void gr_opengl_clear()
580 {
581         glClearColor(gr_screen.current_clear_color.red / 255.0, 
582                 gr_screen.current_clear_color.green / 255.0, 
583                 gr_screen.current_clear_color.blue / 255.0, 1.0);
584
585         glClear ( GL_COLOR_BUFFER_BIT );
586 }
587
588 void gr_opengl_save_mouse_area(int x, int y, int w, int h);
589 static void opengl_tcache_frame ();
590
591 void gr_opengl_flip()
592 {
593         if (!Inited) return;
594
595         gr_reset_clip();
596
597         mouse_eval_deltas();
598
599         Gr_opengl_mouse_saved = 0;
600         
601         if ( mouse_is_visible() )       {
602                 int mx, my;
603                 
604                 gr_reset_clip();
605                 mouse_get_pos( &mx, &my );
606                 
607                 gr_opengl_save_mouse_area(mx,my,32,32);
608                 
609                 if ( Gr_cursor == -1 )  {
610                         // stuff
611                 } else {
612                         gr_set_bitmap(Gr_cursor, GR_ALPHABLEND_NONE, GR_BITBLT_MODE_NORMAL, 1.0f, -1, -1);
613                         gr_bitmap( mx, my );
614                 }
615          }
616          
617 #ifndef NDEBUG
618         GLenum error = glGetError();
619         int ic = 0;
620         do {
621                 error = glGetError();
622                 
623                 if (error != GL_NO_ERROR) {
624                         nprintf(("Warning", "!!DEBUG!! OpenGL Error: %d (%d this frame)\n", error, ic));
625                 }
626                 ic++;
627         } while (error != GL_NO_ERROR);
628 #endif
629         
630         SDL_GL_SwapBuffers ();
631
632         opengl_tcache_frame ();
633         
634         int cnt = GL_activate;
635         if ( cnt )      {
636                 GL_activate-=cnt;
637                 opengl_tcache_flush();
638                 // gr_opengl_clip_cursor(1); /* mouse grab, see opengl_activate */
639         }
640         
641         cnt = GL_deactivate;
642         if ( cnt )      {
643                 GL_deactivate-=cnt;
644                 // gr_opengl_clip_cursor(0);  /* mouse grab, see opengl_activate */
645         }
646 }
647
648 void gr_opengl_flip_window(uint _hdc, int x, int y, int w, int h )
649 {
650         // Not used.
651 }
652
653 void gr_opengl_set_clip(int x,int y,int w,int h)
654 {
655         // check for sanity of parameters
656         if (x < 0)
657                 x = 0;
658         if (y < 0)
659                 y = 0;
660
661         if (x >= gr_screen.max_w)
662                 x = gr_screen.max_w - 1;
663         if (y >= gr_screen.max_h)
664                 y = gr_screen.max_h - 1;
665
666         if (x + w > gr_screen.max_w)
667                 w = gr_screen.max_w - x;
668         if (y + h > gr_screen.max_h)
669                 h = gr_screen.max_h - y;
670         
671         if (w > gr_screen.max_w)
672                 w = gr_screen.max_w;
673         if (h > gr_screen.max_h)
674                 h = gr_screen.max_h;
675         
676         gr_screen.offset_x = x;
677         gr_screen.offset_y = y;
678         gr_screen.clip_left = 0;
679         gr_screen.clip_right = w-1;
680         gr_screen.clip_top = 0;
681         gr_screen.clip_bottom = h-1;
682         gr_screen.clip_width = w;
683         gr_screen.clip_height = h;
684         
685         glEnable(GL_SCISSOR_TEST);
686         glScissor(x, gr_screen.max_h-y-h, w, h);
687 }
688
689 void gr_opengl_reset_clip()
690 {
691         gr_screen.offset_x = 0;
692         gr_screen.offset_y = 0;
693         gr_screen.clip_left = 0;
694         gr_screen.clip_top = 0;
695         gr_screen.clip_right = gr_screen.max_w - 1;
696         gr_screen.clip_bottom = gr_screen.max_h - 1;
697         gr_screen.clip_width = gr_screen.max_w;
698         gr_screen.clip_height = gr_screen.max_h;
699         
700         glDisable(GL_SCISSOR_TEST);
701 //      glScissor(0, 0, gr_screen.max_w, gr_screen.max_h);
702 }
703
704 void gr_opengl_set_bitmap( int bitmap_num, int alphablend_mode = GR_ALPHABLEND_NONE, int bitblt_mode = GR_BITBLT_MODE_NORMAL, float alpha = 1.0f, int sx = -1, int sy = -1 )
705 {
706         gr_screen.current_alpha = alpha;
707         gr_screen.current_alphablend_mode = alphablend_mode;
708         gr_screen.current_bitblt_mode = bitblt_mode;
709         gr_screen.current_bitmap = bitmap_num;
710
711         gr_screen.current_bitmap_sx = sx;
712         gr_screen.current_bitmap_sy = sy;
713 }
714
715 void gr_opengl_create_shader(shader * shade, float r, float g, float b, float c )
716 {
717         shade->screen_sig = gr_screen.signature;
718         shade->r = r;
719         shade->g = g;
720         shade->b = b;
721         shade->c = c;   
722 }
723
724 void gr_opengl_set_shader( shader * shade )
725 {       
726         if ( shade )    {
727                 if (shade->screen_sig != gr_screen.signature)   {
728                         gr_create_shader( shade, shade->r, shade->g, shade->b, shade->c );
729                 }
730                 gr_screen.current_shader = *shade;
731         } else {
732                 gr_create_shader( &gr_screen.current_shader, 0.0f, 0.0f, 0.0f, 0.0f );
733         }
734 }
735
736
737 void gr_opengl_bitmap_ex(int x,int y,int w,int h,int sx,int sy)
738 {
739         STUB_FUNCTION; /* who called me? */
740 }
741
742 void gr_opengl_bitmap(int x, int y)
743 {
744         STUB_FUNCTION; /* who called me? */
745 }
746
747 static void gr_opengl_rect_internal(int x, int y, int w, int h, int r, int g, int b, int a)
748 {
749         int saved_zbuf;
750         vertex v[4];
751         vertex *verts[4] = {&v[0], &v[1], &v[2], &v[3]};
752
753         saved_zbuf = gr_zbuffer_get();
754         
755         // start the frame, no zbuffering, no culling
756         g3_start_frame(1);      
757         gr_zbuffer_set(GR_ZBUFF_NONE);          
758         gr_set_cull(0);         
759
760         // stuff coords         
761         v[0].sx = i2fl(x);
762         v[0].sy = i2fl(y);
763         v[0].sw = 0.0f;
764         v[0].u = 0.0f;
765         v[0].v = 0.0f;
766         v[0].flags = PF_PROJECTED;
767         v[0].codes = 0;
768         v[0].r = (ubyte)r;
769         v[0].g = (ubyte)g;
770         v[0].b = (ubyte)b;
771         v[0].a = (ubyte)a;
772
773         v[1].sx = i2fl(x + w);
774         v[1].sy = i2fl(y);      
775         v[1].sw = 0.0f;
776         v[1].u = 0.0f;
777         v[1].v = 0.0f;
778         v[1].flags = PF_PROJECTED;
779         v[1].codes = 0;
780         v[1].r = (ubyte)r;
781         v[1].g = (ubyte)g;
782         v[1].b = (ubyte)b;
783         v[1].a = (ubyte)a;
784
785         v[2].sx = i2fl(x + w);
786         v[2].sy = i2fl(y + h);
787         v[2].sw = 0.0f;
788         v[2].u = 0.0f;
789         v[2].v = 0.0f;
790         v[2].flags = PF_PROJECTED;
791         v[2].codes = 0;
792         v[2].r = (ubyte)r;
793         v[2].g = (ubyte)g;
794         v[2].b = (ubyte)b;
795         v[2].a = (ubyte)a;
796
797         v[3].sx = i2fl(x);
798         v[3].sy = i2fl(y + h);
799         v[3].sw = 0.0f;
800         v[3].u = 0.0f;
801         v[3].v = 0.0f;
802         v[3].flags = PF_PROJECTED;
803         v[3].codes = 0;                         
804         v[3].r = (ubyte)r;
805         v[3].g = (ubyte)g;
806         v[3].b = (ubyte)b;
807         v[3].a = (ubyte)a;
808
809         // draw the polys
810         g3_draw_poly_constant_sw(4, verts, TMAP_FLAG_GOURAUD | TMAP_FLAG_RGB | TMAP_FLAG_ALPHA, 0.1f);          
811
812         g3_end_frame();
813
814         // restore zbuffer and culling
815         gr_zbuffer_set(saved_zbuf);
816         gr_set_cull(1); 
817 }
818
819 void gr_opengl_rect(int x,int y,int w,int h)
820 {
821         gr_opengl_rect_internal(x, y, w, h, gr_screen.current_color.red, gr_screen.current_color.green, gr_screen.current_color.blue, gr_screen.current_color.alpha);
822 }
823
824 void gr_opengl_shade(int x,int y,int w,int h)
825 {
826         int r,g,b,a;
827         
828         float shade1 = 1.0f;
829         float shade2 = 6.0f;
830
831         r = fl2i(gr_screen.current_shader.r*255.0f*shade1);
832         if ( r < 0 ) r = 0; else if ( r > 255 ) r = 255;
833         g = fl2i(gr_screen.current_shader.g*255.0f*shade1);
834         if ( g < 0 ) g = 0; else if ( g > 255 ) g = 255;
835         b = fl2i(gr_screen.current_shader.b*255.0f*shade1);
836         if ( b < 0 ) b = 0; else if ( b > 255 ) b = 255;
837         a = fl2i(gr_screen.current_shader.c*255.0f*shade2);
838         if ( a < 0 ) a = 0; else if ( a > 255 ) a = 255;
839
840         gr_opengl_rect_internal(x, y, w, h, r, g, b, a);        
841 }
842
843 static void gr_opengl_aabitmap_ex_internal(int x,int y,int w,int h,int sx,int sy)
844 {
845         if ( w < 1 ) return;
846         if ( h < 1 ) return;
847
848         if ( !gr_screen.current_color.is_alphacolor )   return;
849
850         float u_scale, v_scale;
851
852         if ( !gr_tcache_set( gr_screen.current_bitmap, TCACHE_TYPE_AABITMAP, &u_scale, &v_scale, 0, -1, -1, 0 ) )       {
853                 // Couldn't set texture
854                 mprintf(( "WARNING: Error setting aabitmap texture!\n" ));
855                 return;
856         }
857
858         gr_opengl_set_state( TEXTURE_SOURCE_NO_FILTERING, ALPHA_BLEND_ALPHA_BLEND_ALPHA, ZBUFFER_TYPE_NONE );
859         
860         float u0, u1, v0, v1;
861         float x1, x2, y1, y2;
862         int bw, bh;
863
864         bm_get_info( gr_screen.current_bitmap, &bw, &bh );
865
866         u0 = u_scale*i2fl(sx)/i2fl(bw);
867         v0 = v_scale*i2fl(sy)/i2fl(bh);
868
869         u1 = u_scale*i2fl(sx+w)/i2fl(bw);
870         v1 = v_scale*i2fl(sy+h)/i2fl(bh);
871
872         x1 = i2fl(x+gr_screen.offset_x);
873         y1 = i2fl(y+gr_screen.offset_y);
874         x2 = i2fl(x+w+gr_screen.offset_x);
875         y2 = i2fl(y+h+gr_screen.offset_y);
876
877         if ( gr_screen.current_color.is_alphacolor )    {
878                 glColor4ub(gr_screen.current_color.red, gr_screen.current_color.green, gr_screen.current_color.blue,gr_screen.current_color.alpha);
879         } else {
880                 glColor3ub(gr_screen.current_color.red, gr_screen.current_color.green, gr_screen.current_color.blue);
881         }
882
883         glBegin (GL_QUADS);
884           glTexCoord2f (u0, v1);
885           glVertex3f (x1, y2, -0.99);
886
887           glTexCoord2f (u1, v1);
888           glVertex3f (x2, y2, -0.99);
889
890           glTexCoord2f (u1, v0);
891           glVertex3f (x2, y1, -0.99);
892
893           glTexCoord2f (u0, v0);
894           glVertex3f (x1, y1, -0.99);
895         glEnd ();
896 }
897
898 void gr_opengl_aabitmap_ex(int x,int y,int w,int h,int sx,int sy)
899 {
900         int reclip;
901         #ifndef NDEBUG
902         int count = 0;
903         #endif
904
905         int dx1=x, dx2=x+w-1;
906         int dy1=y, dy2=y+h-1;
907
908         int bw, bh;
909         bm_get_info( gr_screen.current_bitmap, &bw, &bh, NULL );
910
911         do {
912                 reclip = 0;
913                 #ifndef NDEBUG
914                         if ( count > 1 ) Int3();
915                         count++;
916                 #endif
917         
918                 if ((dx1 > gr_screen.clip_right ) || (dx2 < gr_screen.clip_left)) return;
919                 if ((dy1 > gr_screen.clip_bottom ) || (dy2 < gr_screen.clip_top)) return;
920                 if ( dx1 < gr_screen.clip_left ) { sx += gr_screen.clip_left-dx1; dx1 = gr_screen.clip_left; }
921                 if ( dy1 < gr_screen.clip_top ) { sy += gr_screen.clip_top-dy1; dy1 = gr_screen.clip_top; }
922                 if ( dx2 > gr_screen.clip_right )       { dx2 = gr_screen.clip_right; }
923                 if ( dy2 > gr_screen.clip_bottom )      { dy2 = gr_screen.clip_bottom; }
924
925                 if ( sx < 0 ) {
926                         dx1 -= sx;
927                         sx = 0;
928                         reclip = 1;
929                 }
930
931                 if ( sy < 0 ) {
932                         dy1 -= sy;
933                         sy = 0;
934                         reclip = 1;
935                 }
936
937                 w = dx2-dx1+1;
938                 h = dy2-dy1+1;
939
940                 if ( sx + w > bw ) {
941                         w = bw - sx;
942                         dx2 = dx1 + w - 1;
943                 }
944
945                 if ( sy + h > bh ) {
946                         h = bh - sy;
947                         dy2 = dy1 + h - 1;
948                 }
949
950                 if ( w < 1 ) return;            // clipped away!
951                 if ( h < 1 ) return;            // clipped away!
952
953         } while (reclip);
954
955         // Make sure clipping algorithm works
956         #ifndef NDEBUG
957                 Assert( w > 0 );
958                 Assert( h > 0 );
959                 Assert( w == (dx2-dx1+1) );
960                 Assert( h == (dy2-dy1+1) );
961                 Assert( sx >= 0 );
962                 Assert( sy >= 0 );
963                 Assert( sx+w <= bw );
964                 Assert( sy+h <= bh );
965                 Assert( dx2 >= dx1 );
966                 Assert( dy2 >= dy1 );
967                 Assert( (dx1 >= gr_screen.clip_left ) && (dx1 <= gr_screen.clip_right) );
968                 Assert( (dx2 >= gr_screen.clip_left ) && (dx2 <= gr_screen.clip_right) );
969                 Assert( (dy1 >= gr_screen.clip_top ) && (dy1 <= gr_screen.clip_bottom) );
970                 Assert( (dy2 >= gr_screen.clip_top ) && (dy2 <= gr_screen.clip_bottom) );
971         #endif
972
973         // We now have dx1,dy1 and dx2,dy2 and sx, sy all set validly within clip regions.
974         gr_opengl_aabitmap_ex_internal(dx1,dy1,dx2-dx1+1,dy2-dy1+1,sx,sy);
975 }
976
977 void gr_opengl_aabitmap(int x, int y)
978 {
979         int w, h;
980
981         bm_get_info( gr_screen.current_bitmap, &w, &h, NULL );
982         int dx1=x, dx2=x+w-1;
983         int dy1=y, dy2=y+h-1;
984         int sx=0, sy=0;
985
986         if ((dx1 > gr_screen.clip_right ) || (dx2 < gr_screen.clip_left)) return;
987         if ((dy1 > gr_screen.clip_bottom ) || (dy2 < gr_screen.clip_top)) return;
988         if ( dx1 < gr_screen.clip_left ) { sx = gr_screen.clip_left-dx1; dx1 = gr_screen.clip_left; }
989         if ( dy1 < gr_screen.clip_top ) { sy = gr_screen.clip_top-dy1; dy1 = gr_screen.clip_top; }
990         if ( dx2 > gr_screen.clip_right )       { dx2 = gr_screen.clip_right; }
991         if ( dy2 > gr_screen.clip_bottom )      { dy2 = gr_screen.clip_bottom; }
992
993         if ( sx < 0 ) return;
994         if ( sy < 0 ) return;
995         if ( sx >= w ) return;
996         if ( sy >= h ) return;
997
998         // Draw bitmap bm[sx,sy] into (dx1,dy1)-(dx2,dy2)
999         gr_aabitmap_ex(dx1,dy1,dx2-dx1+1,dy2-dy1+1,sx,sy);
1000 }
1001
1002 void gr_opengl_string( int sx, int sy, const char *s )
1003 {
1004         int width, spacing, letter;
1005         int x, y;
1006
1007         if ( !Current_font )    {
1008                 return;
1009         }
1010
1011         gr_set_bitmap(Current_font->bitmap_id, GR_ALPHABLEND_NONE, GR_BITBLT_MODE_NORMAL, 1.0f, -1, -1);
1012
1013         x = sx;
1014         y = sy;
1015
1016         if (sx==0x8000) {                       //centered
1017                 x = get_centered_x(s);
1018         } else {
1019                 x = sx;
1020         }
1021         
1022         spacing = 0;
1023
1024         while (*s)      {
1025                 x += spacing;
1026
1027                 while (*s== '\n' )      {
1028                         s++;
1029                         y += Current_font->h;
1030                         if (sx==0x8000) {                       //centered
1031                                 x = get_centered_x(s);
1032                         } else {
1033                                 x = sx;
1034                         }
1035                 }
1036                 if (*s == 0 ) break;
1037
1038                 letter = get_char_width(s[0],s[1],&width,&spacing);
1039                 s++;
1040
1041                 //not in font, draw as space
1042                 if (letter<0)   {
1043                         continue;
1044                 }
1045
1046                 int xd, yd, xc, yc;
1047                 int wc, hc;
1048
1049                 // Check if this character is totally clipped
1050                 if ( x + width < gr_screen.clip_left ) continue;
1051                 if ( y + Current_font->h < gr_screen.clip_top ) continue;
1052                 if ( x > gr_screen.clip_right ) continue;
1053                 if ( y > gr_screen.clip_bottom ) continue;
1054
1055                 xd = yd = 0;
1056                 if ( x < gr_screen.clip_left ) xd = gr_screen.clip_left - x;
1057                 if ( y < gr_screen.clip_top ) yd = gr_screen.clip_top - y;
1058                 xc = x+xd;
1059                 yc = y+yd;
1060
1061                 wc = width - xd; hc = Current_font->h - yd;
1062                 if ( xc + wc > gr_screen.clip_right ) wc = gr_screen.clip_right - xc;
1063                 if ( yc + hc > gr_screen.clip_bottom ) hc = gr_screen.clip_bottom - yc;
1064
1065                 if ( wc < 1 ) continue;
1066                 if ( hc < 1 ) continue;
1067
1068                 int u = Current_font->bm_u[letter];
1069                 int v = Current_font->bm_v[letter];
1070
1071                 gr_opengl_aabitmap_ex_internal( xc, yc, wc, hc, u+xd, v+yd );
1072         }
1073 }
1074
1075 void gr_opengl_line(int x1,int y1,int x2,int y2)
1076 {
1077         int clipped = 0, swapped=0;
1078
1079         gr_opengl_set_state( TEXTURE_SOURCE_NONE, ALPHA_BLEND_ALPHA_BLEND_ALPHA, ZBUFFER_TYPE_NONE );
1080         
1081         INT_CLIPLINE(x1,y1,x2,y2,gr_screen.clip_left,gr_screen.clip_top,gr_screen.clip_right,gr_screen.clip_bottom,return,clipped=1,swapped=1);
1082         
1083         float sx1, sy1;
1084         float sx2, sy2;
1085         
1086         sx1 = i2fl(x1 + gr_screen.offset_x)+0.5;
1087         sy1 = i2fl(y1 + gr_screen.offset_y)+0.5;
1088         sx2 = i2fl(x2 + gr_screen.offset_x)+0.5;
1089         sy2 = i2fl(y2 + gr_screen.offset_y)+0.5;
1090         
1091         if ( x1 == x2 && y1 == y2 ) {
1092                 glBegin (GL_POINTS);
1093                   glColor4ub (gr_screen.current_color.red, gr_screen.current_color.green, gr_screen.current_color.blue, gr_screen.current_color.alpha);
1094                   glVertex3f (sx1, sy1, -0.99f);
1095                 glEnd ();
1096                 
1097                 return;
1098         }
1099         
1100         if ( x1 == x2 ) {
1101                 if ( sy1 < sy2 )    {
1102                         sy2 += 0.5f;
1103                 } else {
1104                         sy1 += 0.5f;
1105                 }
1106         } else if ( y1 == y2 )  {
1107                 if ( sx1 < sx2 )    {
1108                         sx2 += 0.5f;
1109                 } else {
1110                         sx1 += 0.5f;
1111                 }
1112         }
1113         
1114         glBegin (GL_LINES);
1115           glColor4ub (gr_screen.current_color.red, gr_screen.current_color.green, gr_screen.current_color.blue, gr_screen.current_color.alpha);
1116           glVertex3f (sx2, sy2, -0.99f);
1117           glVertex3f (sx1, sy1, -0.99f);
1118         glEnd ();
1119 }
1120
1121 void gr_opengl_aaline(vertex *v1, vertex *v2)
1122 {
1123         gr_opengl_line( fl2i(v1->sx), fl2i(v1->sy), fl2i(v2->sx), fl2i(v2->sy) );
1124 }
1125
1126 void gr_opengl_gradient(int x1,int y1,int x2,int y2)
1127 {
1128         int clipped = 0, swapped=0;
1129
1130         if ( !gr_screen.current_color.is_alphacolor )   {
1131                 gr_line( x1, y1, x2, y2 );
1132                 return;
1133         }
1134
1135         INT_CLIPLINE(x1,y1,x2,y2,gr_screen.clip_left,gr_screen.clip_top,gr_screen.clip_right,gr_screen.clip_bottom,return,clipped=1,swapped=1);
1136
1137         gr_opengl_set_state( TEXTURE_SOURCE_NONE, ALPHA_BLEND_ALPHA_BLEND_ALPHA, ZBUFFER_TYPE_NONE );
1138
1139         int aa = swapped ? 0 : gr_screen.current_color.alpha;
1140         int ba = swapped ? gr_screen.current_color.alpha : 0;
1141         
1142         float sx1, sy1;
1143         float sx2, sy2;
1144         
1145         sx1 = i2fl(x1 + gr_screen.offset_x)+0.5;
1146         sy1 = i2fl(y1 + gr_screen.offset_y)+0.5;
1147         sx2 = i2fl(x2 + gr_screen.offset_x)+0.5;
1148         sy2 = i2fl(y2 + gr_screen.offset_y)+0.5;
1149
1150         if ( x1 == x2 ) {
1151                 if ( sy1 < sy2 )    {
1152                         sy2 += 0.5f;
1153                 } else {
1154                         sy1 += 0.5f;
1155                 }
1156         } else if ( y1 == y2 )  {
1157                 if ( sx1 < sx2 )    {
1158                         sx2 += 0.5f;
1159                 } else {
1160                         sx1 += 0.5f;
1161                 }
1162         }
1163         
1164         glBegin (GL_LINES);
1165           glColor4ub (gr_screen.current_color.red, gr_screen.current_color.green, gr_screen.current_color.blue, ba);
1166           glVertex3f (sx2, sy2, -0.99f);
1167           glColor4ub (gr_screen.current_color.red, gr_screen.current_color.green, gr_screen.current_color.blue, aa);
1168           glVertex3f (sx1, sy1, -0.99f);
1169         glEnd ();       
1170 }
1171
1172 void gr_opengl_circle( int xc, int yc, int d )
1173 {
1174         int p,x, y, r;
1175
1176         r = d/2;
1177         p=3-d;
1178         x=0;
1179         y=r;
1180
1181         // Big clip
1182         if ( (xc+r) < gr_screen.clip_left ) return;
1183         if ( (xc-r) > gr_screen.clip_right ) return;
1184         if ( (yc+r) < gr_screen.clip_top ) return;
1185         if ( (yc-r) > gr_screen.clip_bottom ) return;
1186
1187         while(x<y)      {
1188                 // Draw the first octant
1189                 gr_opengl_line( xc-y, yc-x, xc+y, yc-x );
1190                 gr_opengl_line( xc-y, yc+x, xc+y, yc+x );
1191                                 
1192                 if (p<0) 
1193                         p=p+(x<<2)+6;
1194                 else    {
1195                         // Draw the second octant
1196                         gr_opengl_line( xc-x, yc-y, xc+x, yc-y );
1197                         gr_opengl_line( xc-x, yc+y, xc+x, yc+y );
1198                                                 
1199                         p=p+((x-y)<<2)+10;
1200                         y--;
1201                 }
1202                 x++;
1203         }
1204         if(x==y) {
1205                 gr_opengl_line( xc-x, yc-y, xc+x, yc-y );
1206                 gr_opengl_line( xc-x, yc+y, xc+x, yc+y );
1207         }
1208         return;
1209 }
1210
1211 static void gr_opengl_stuff_fog_value(float z, int *r, int *g, int *b, int *a)
1212 {
1213         float f_float;
1214         
1215         f_float = (gr_screen.fog_far - z) / (gr_screen.fog_far - gr_screen.fog_near);
1216         if (f_float < 0.0f) {
1217                 f_float = 0.0f;
1218         } else {
1219                 f_float = 1.0f;
1220         }
1221         *r = 0;
1222         *g = 0;
1223         *b = 0;
1224         *a = (int)(f_float * 255.0);
1225 }
1226
1227 static void gr_opengl_tmapper_internal( int nv, vertex ** verts, uint flags, int is_scaler )
1228 {
1229         int i;
1230         float u_scale = 1.0f, v_scale = 1.0f;
1231
1232         // Make nebula use the texture mapper... this blends the colors better.
1233         if ( flags & TMAP_FLAG_NEBULA ){
1234                 Int3 ();
1235         }
1236
1237         gr_texture_source texture_source = (gr_texture_source)-1;
1238         gr_alpha_blend alpha_blend = (gr_alpha_blend)-1;
1239         gr_zbuffer_type zbuffer_type = (gr_zbuffer_type)-1;
1240         
1241         if ( gr_zbuffering )    {
1242                 if ( is_scaler || (gr_screen.current_alphablend_mode == GR_ALPHABLEND_FILTER)   )       {
1243                         zbuffer_type = ZBUFFER_TYPE_READ;
1244                 } else {
1245                         zbuffer_type = ZBUFFER_TYPE_FULL;
1246                 }
1247         } else {
1248                 zbuffer_type = ZBUFFER_TYPE_NONE;
1249         }
1250         
1251         int alpha;
1252
1253         int tmap_type = TCACHE_TYPE_NORMAL;
1254
1255         int r, g, b;
1256
1257         if ( flags & TMAP_FLAG_TEXTURED )       {
1258                 r = g = b = 255;
1259         } else {
1260                 r = gr_screen.current_color.red;
1261                 g = gr_screen.current_color.green;
1262                 b = gr_screen.current_color.blue;
1263         }
1264
1265         if ( gr_screen.current_alphablend_mode == GR_ALPHABLEND_FILTER )        
1266         {
1267                 if (1) {
1268                         tmap_type = TCACHE_TYPE_NORMAL;
1269                         alpha_blend = ALPHA_BLEND_ALPHA_ADDITIVE;
1270                         
1271                         // Blend with screen pixel using src*alpha+dst
1272                         float factor = gr_screen.current_alpha;
1273                         
1274                         alpha = 255;
1275                         
1276                         if ( factor <= 1.0f )   {
1277                                 int tmp_alpha = fl2i(gr_screen.current_alpha*255.0f);
1278                                 r = (r*tmp_alpha)/255;
1279                                 g = (g*tmp_alpha)/255;
1280                                 b = (b*tmp_alpha)/255;
1281                         }
1282                 } else {
1283                         tmap_type = TCACHE_TYPE_XPARENT;
1284                         
1285                         alpha_blend = ALPHA_BLEND_ALPHA_BLEND_ALPHA;
1286                         
1287                         // Blend with screen pixel using src*alpha+dst
1288                         float factor = gr_screen.current_alpha;
1289                                 
1290                         if ( factor > 1.0f )    {
1291                                 alpha = 255;
1292                         } else {
1293                                 alpha = fl2i(gr_screen.current_alpha*255.0f);
1294                         }
1295                 }
1296         } else {
1297                 if(Bm_pixel_format == BM_PIXEL_FORMAT_ARGB) {
1298                         alpha_blend = ALPHA_BLEND_ALPHA_BLEND_ALPHA;
1299                 } else {
1300                         alpha_blend = ALPHA_BLEND_NONE;
1301                 }
1302                 alpha = 255;
1303         }
1304
1305         if(flags & TMAP_FLAG_BITMAP_SECTION){
1306                 tmap_type = TCACHE_TYPE_BITMAP_SECTION;
1307         }
1308         
1309         texture_source = TEXTURE_SOURCE_NONE;
1310         
1311         if ( flags & TMAP_FLAG_TEXTURED )       {
1312                 if ( !gr_tcache_set(gr_screen.current_bitmap, tmap_type, &u_scale, &v_scale, 0, gr_screen.current_bitmap_sx, gr_screen.current_bitmap_sy, 0 ))
1313                 {
1314                         mprintf(( "Not rendering a texture because it didn't fit in VRAM!\n" ));
1315                         return;
1316                 }
1317
1318                 // use nonfiltered textures for bitmap sections
1319                 if(flags & TMAP_FLAG_BITMAP_SECTION){
1320                         texture_source = TEXTURE_SOURCE_NO_FILTERING;
1321                 } else {
1322                         texture_source = TEXTURE_SOURCE_DECAL;
1323                 }
1324         }
1325
1326
1327         gr_opengl_set_state( texture_source, alpha_blend, zbuffer_type );
1328         
1329         if ( flags & TMAP_FLAG_TEXTURED )
1330         {
1331                 // rendition junk
1332                 // STUB_FUNCTION;
1333         }
1334
1335         if (flags & TMAP_FLAG_PIXEL_FOG) {
1336                 int r, g, b;
1337                 int ra, ga, ba;
1338                 ra = ga = ba = 0;
1339         
1340                 /* argh */
1341                 for (i=nv-1;i>=0;i--)   // DDOI - change polygon winding
1342                 {
1343                         vertex * va = verts[i];
1344                         float sx, sy;
1345                 
1346                         int x, y;
1347                         x = fl2i(va->sx*16.0f);
1348                         y = fl2i(va->sy*16.0f);
1349                 
1350                         x += gr_screen.offset_x*16;
1351                         y += gr_screen.offset_y*16;
1352                 
1353                         sx = i2fl(x) / 16.0f;
1354                         sy = i2fl(y) / 16.0f;
1355                 
1356                         neb2_get_pixel((int)sx, (int)sy, &r, &g, &b);
1357                         
1358                         ra += r;
1359                         ga += g;
1360                         ba += b;
1361                 }
1362                 
1363                 ra /= nv;
1364                 ga /= nv;
1365                 ba /= nv;
1366                 
1367                 gr_fog_set(GR_FOGMODE_FOG, ra, ga, ba, -1.0f, -1.0f);
1368         }
1369         
1370         glBegin(GL_TRIANGLE_FAN);
1371         for (i = nv-1; i >= 0; i--) {           
1372                 vertex * va = verts[i];
1373                 float sx, sy, sz;
1374                 float tu, tv;
1375                 float rhw;
1376                 int a;
1377                 
1378                 if ( gr_zbuffering || (flags & TMAP_FLAG_NEBULA) )      {
1379                         sz = 1.0 - 1.0 / (1.0 + va->z / (32768.0 / 256.0));
1380                         
1381                         if ( sz > 0.98f ) {
1382                                 sz = 0.98f;
1383                         }
1384                 } else {
1385                         sz = 0.99f;
1386                 }
1387
1388                 if ( flags & TMAP_FLAG_CORRECT )        {
1389                         rhw = va->sw;
1390                 } else {
1391                         rhw = 1.0f;
1392                 }
1393                 
1394                 if (flags & TMAP_FLAG_ALPHA) {
1395                         a = verts[i]->a;
1396                 } else {
1397                         a = alpha;
1398                 }
1399
1400                 if (flags & TMAP_FLAG_NEBULA ) {
1401                         int pal = (verts[i]->b*(NEBULA_COLORS-1))/255;
1402                         r = gr_palette[pal*3+0];
1403                         g = gr_palette[pal*3+1];
1404                         b = gr_palette[pal*3+2];
1405                 } else if ( (flags & TMAP_FLAG_RAMP) && (flags & TMAP_FLAG_GOURAUD) )   {
1406                         r = Gr_gamma_lookup[verts[i]->b];
1407                         g = Gr_gamma_lookup[verts[i]->b];
1408                         b = Gr_gamma_lookup[verts[i]->b];
1409                 } else if ( (flags & TMAP_FLAG_RGB)  && (flags & TMAP_FLAG_GOURAUD) )   {
1410                         // Make 0.75 be 256.0f
1411                         r = Gr_gamma_lookup[verts[i]->r];
1412                         g = Gr_gamma_lookup[verts[i]->g];
1413                         b = Gr_gamma_lookup[verts[i]->b];
1414                 } else {
1415                         // use constant RGB values...
1416                 }
1417                 glColor4ub (r,g,b,a);
1418
1419                 if((gr_screen.current_fog_mode != GR_FOGMODE_NONE) && (D3D_fog_mode == 1)){
1420                         int sr, sg, sb, sa;
1421                         
1422                         /* this is for GL_EXT_SECONDARY_COLOR */
1423                         gr_opengl_stuff_fog_value(va->z, &sr, &sg, &sb, &sa);
1424                         /* do separate color call here */
1425                         
1426                         STUB_FUNCTION;
1427                 }
1428                 
1429                 int x, y;
1430                 x = fl2i(va->sx*16.0f);
1431                 y = fl2i(va->sy*16.0f);
1432
1433                 x += gr_screen.offset_x*16;
1434                 y += gr_screen.offset_y*16;
1435                 
1436                 sx = i2fl(x) / 16.0f;
1437                 sy = i2fl(y) / 16.0f;
1438
1439                 if ( flags & TMAP_FLAG_TEXTURED )       {
1440                         tu = va->u*u_scale;
1441                         tv = va->v*v_scale;
1442                         glTexCoord2f(tu, tv);
1443                 }
1444                 
1445                 glVertex4f(sx/rhw, sy/rhw, -sz/rhw, 1.0/rhw);
1446         }
1447         glEnd();
1448 }
1449
1450 void gr_opengl_tmapper( int nverts, vertex **verts, uint flags )
1451 {
1452         gr_opengl_tmapper_internal( nverts, verts, flags, 0 );
1453 }
1454
1455 #define FIND_SCALED_NUM(x,x0,x1,y0,y1) (((((x)-(x0))*((y1)-(y0)))/((x1)-(x0)))+(y0))
1456
1457 void gr_opengl_scaler(vertex *va, vertex *vb )
1458 {
1459         float x0, y0, x1, y1;
1460         float u0, v0, u1, v1;
1461         float clipped_x0, clipped_y0, clipped_x1, clipped_y1;
1462         float clipped_u0, clipped_v0, clipped_u1, clipped_v1;
1463         float xmin, xmax, ymin, ymax;
1464         int dx0, dy0, dx1, dy1;
1465
1466         //============= CLIP IT =====================
1467
1468         x0 = va->sx; y0 = va->sy;
1469         x1 = vb->sx; y1 = vb->sy;
1470
1471         xmin = i2fl(gr_screen.clip_left); ymin = i2fl(gr_screen.clip_top);
1472         xmax = i2fl(gr_screen.clip_right); ymax = i2fl(gr_screen.clip_bottom);
1473
1474         u0 = va->u; v0 = va->v;
1475         u1 = vb->u; v1 = vb->v;
1476
1477         // Check for obviously offscreen bitmaps...
1478         if ( (y1<=y0) || (x1<=x0) ) return;
1479         if ( (x1<xmin ) || (x0>xmax) ) return;
1480         if ( (y1<ymin ) || (y0>ymax) ) return;
1481
1482         clipped_u0 = u0; clipped_v0 = v0;
1483         clipped_u1 = u1; clipped_v1 = v1;
1484
1485         clipped_x0 = x0; clipped_y0 = y0;
1486         clipped_x1 = x1; clipped_y1 = y1;
1487
1488         // Clip the left, moving u0 right as necessary
1489         if ( x0 < xmin )        {
1490                 clipped_u0 = FIND_SCALED_NUM(xmin,x0,x1,u0,u1);
1491                 clipped_x0 = xmin;
1492         }
1493
1494         // Clip the right, moving u1 left as necessary
1495         if ( x1 > xmax )        {
1496                 clipped_u1 = FIND_SCALED_NUM(xmax,x0,x1,u0,u1);
1497                 clipped_x1 = xmax;
1498         }
1499
1500         // Clip the top, moving v0 down as necessary
1501         if ( y0 < ymin )        {
1502                 clipped_v0 = FIND_SCALED_NUM(ymin,y0,y1,v0,v1);
1503                 clipped_y0 = ymin;
1504         }
1505
1506         // Clip the bottom, moving v1 up as necessary
1507         if ( y1 > ymax )        {
1508                 clipped_v1 = FIND_SCALED_NUM(ymax,y0,y1,v0,v1);
1509                 clipped_y1 = ymax;
1510         }
1511         
1512         dx0 = fl2i(clipped_x0); dx1 = fl2i(clipped_x1);
1513         dy0 = fl2i(clipped_y0); dy1 = fl2i(clipped_y1);
1514
1515         if (dx1<=dx0) return;
1516         if (dy1<=dy0) return;
1517
1518         //============= DRAW IT =====================
1519
1520         vertex v[4];
1521         vertex *vl[4];
1522
1523         vl[0] = &v[0];  
1524         v->sx = clipped_x0;
1525         v->sy = clipped_y0;
1526         v->sw = va->sw;
1527         v->z = va->z;
1528         v->u = clipped_u0;
1529         v->v = clipped_v0;
1530
1531         vl[1] = &v[1];  
1532         v[1].sx = clipped_x1;
1533         v[1].sy = clipped_y0;
1534         v[1].sw = va->sw;
1535         v[1].z = va->z;
1536         v[1].u = clipped_u1;
1537         v[1].v = clipped_v0;
1538
1539         vl[2] = &v[2];  
1540         v[2].sx = clipped_x1;
1541         v[2].sy = clipped_y1;
1542         v[2].sw = va->sw;
1543         v[2].z = va->z;
1544         v[2].u = clipped_u1;
1545         v[2].v = clipped_v1;
1546
1547         vl[3] = &v[3];  
1548         v[3].sx = clipped_x0;
1549         v[3].sy = clipped_y1;
1550         v[3].sw = va->sw;
1551         v[3].z = va->z;
1552         v[3].u = clipped_u0;
1553         v[3].v = clipped_v1;
1554
1555         gr_opengl_tmapper_internal( 4, vl, TMAP_FLAG_TEXTURED, 1 );
1556 }
1557
1558 void gr_opengl_set_palette(ubyte *new_palette, int is_alphacolor)
1559 {
1560 }
1561
1562 void gr_opengl_get_color( int * r, int * g, int * b )
1563 {
1564         if (r) *r = gr_screen.current_color.red;
1565         if (g) *g = gr_screen.current_color.green;
1566         if (b) *b = gr_screen.current_color.blue;
1567 }
1568
1569 void gr_opengl_init_color(color *c, int r, int g, int b)
1570 {
1571         c->screen_sig = gr_screen.signature;
1572         c->red = (unsigned char)r;
1573         c->green = (unsigned char)g;
1574         c->blue = (unsigned char)b;
1575         c->alpha = 255;
1576         c->ac_type = AC_TYPE_NONE;
1577         c->alphacolor = -1;
1578         c->is_alphacolor = 0;
1579         c->magic = 0xAC01;
1580 }
1581
1582 void gr_opengl_init_alphacolor( color *clr, int r, int g, int b, int alpha, int type )
1583 {
1584         if ( r < 0 ) r = 0; else if ( r > 255 ) r = 255;
1585         if ( g < 0 ) g = 0; else if ( g > 255 ) g = 255;
1586         if ( b < 0 ) b = 0; else if ( b > 255 ) b = 255;
1587         if ( alpha < 0 ) alpha = 0; else if ( alpha > 255 ) alpha = 255;
1588
1589         gr_opengl_init_color( clr, r, g, b );
1590
1591         clr->alpha = (unsigned char)alpha;
1592         clr->ac_type = (ubyte)type;
1593         clr->alphacolor = -1;
1594         clr->is_alphacolor = 1;
1595 }
1596
1597 void gr_opengl_set_color( int r, int g, int b )
1598 {
1599         Assert((r >= 0) && (r < 256));
1600         Assert((g >= 0) && (g < 256));
1601         Assert((b >= 0) && (b < 256));
1602
1603         gr_opengl_init_color( &gr_screen.current_color, r, g, b );      
1604 }
1605
1606 void gr_opengl_set_color_fast(color *dst)
1607 {
1608         if ( dst->screen_sig != gr_screen.signature )   {
1609                 if ( dst->is_alphacolor )       {
1610                         gr_opengl_init_alphacolor( dst, dst->red, dst->green, dst->blue, dst->alpha, dst->ac_type );
1611                 } else {
1612                         gr_opengl_init_color( dst, dst->red, dst->green, dst->blue );
1613                 }
1614         }
1615         gr_screen.current_color = *dst;
1616 }
1617
1618 void gr_opengl_print_screen(const char *filename)
1619 {
1620 #ifdef GL_VERSION_1_2
1621         char tmp[MAX_FILENAME_LEN];
1622         ubyte *buf = NULL;
1623
1624         strcpy( tmp, filename );
1625         strcat( tmp, NOX(".tga"));
1626
1627         CFILE *f = cfopen(tmp, "wb", CFILE_NORMAL, CF_TYPE_ROOT);
1628
1629         if (f == NULL)
1630                 return;
1631
1632         // Write the TGA header
1633         cfwrite_ubyte( 0, f );  //      IDLength;
1634         cfwrite_ubyte( 0, f );  //      ColorMapType;
1635         cfwrite_ubyte( 2, f );  //      ImageType;              // 2 = 24bpp, uncompressed, 10=24bpp rle compressed
1636         cfwrite_ushort( 0, f ); // CMapStart;
1637         cfwrite_ushort( 0, f ); //      CMapLength;
1638         cfwrite_ubyte( 0, f );  // CMapDepth;
1639         cfwrite_ushort( 0, f ); //      XOffset;
1640         cfwrite_ushort( 0, f ); //      YOffset;
1641         cfwrite_ushort( (ushort)gr_screen.max_w, f );   //      Width;
1642         cfwrite_ushort( (ushort)gr_screen.max_h, f );   //      Height;
1643         cfwrite_ubyte( 24, f ); //PixelDepth;
1644         cfwrite_ubyte( 0, f );  //ImageDesc;
1645
1646         buf = (ubyte*)malloc(gr_screen.max_w * gr_screen.max_h * 3);
1647
1648         if (buf == NULL)
1649                 return;
1650
1651         memset(buf, 0, gr_screen.max_w * gr_screen.max_h * 3);
1652
1653         glReadPixels(0, 0, gr_screen.max_w, gr_screen.max_h, GL_BGR, GL_UNSIGNED_BYTE, buf);
1654
1655         cfwrite(buf, gr_screen.max_w * gr_screen.max_h * 3, 1, f);
1656
1657         cfclose(f);
1658
1659         free(buf);
1660 #endif
1661 }
1662
1663 int gr_opengl_supports_res_ingame(int res)
1664 {
1665         STUB_FUNCTION;
1666         
1667         return 1;
1668 }
1669
1670 int gr_opengl_supports_res_interface(int res)
1671 {
1672         STUB_FUNCTION;
1673         
1674         return 1;
1675 }
1676
1677 static void opengl_tcache_cleanup ();
1678
1679 void gr_opengl_cleanup()
1680 {
1681         if ( !Inited )  return;
1682
1683
1684         gr_reset_clip();
1685         gr_clear();
1686         gr_flip();
1687
1688         opengl_tcache_cleanup ();
1689
1690         Inited = 0;
1691 }
1692
1693 void gr_opengl_fog_set(int fog_mode, int r, int g, int b, float fog_near, float fog_far)
1694 {
1695         Assert((r >= 0) && (r < 256));
1696         Assert((g >= 0) && (g < 256));
1697         Assert((b >= 0) && (b < 256));
1698         
1699         if (fog_mode == GR_FOGMODE_NONE) {
1700                 if (gr_screen.current_fog_mode != fog_mode) {
1701                         glDisable(GL_FOG);
1702                 }
1703                 gr_screen.current_fog_mode = fog_mode;
1704                 
1705                 return;
1706         }
1707         
1708         if (gr_screen.current_fog_mode != fog_mode) {
1709                 glEnable(GL_FOG);
1710                 
1711                 if (D3D_fog_mode == 2) {
1712                         glFogi(GL_FOG_MODE, GL_LINEAR);
1713                 }
1714                 
1715                 gr_screen.current_fog_mode = fog_mode;
1716         }
1717         
1718         if ( (gr_screen.current_fog_color.red != r) ||
1719                         (gr_screen.current_fog_color.green != g) ||
1720                         (gr_screen.current_fog_color.blue != b) ) {
1721                 GLfloat fc[4];
1722                 
1723                 gr_opengl_init_color( &gr_screen.current_fog_color, r, g, b );
1724         
1725                 fc[0] = (float)r/255.0;
1726                 fc[1] = (float)g/255.0;
1727                 fc[2] = (float)b/255.0;
1728                 fc[3] = 1.0;
1729                 
1730                 glFogfv(GL_FOG_COLOR, fc);
1731         }
1732         
1733         if( (fog_near >= 0.0f) && (fog_far >= 0.0f) && 
1734                         ((fog_near != gr_screen.fog_near) || 
1735                         (fog_far != gr_screen.fog_far)) ) {
1736                 gr_screen.fog_near = fog_near;
1737                 gr_screen.fog_far = fog_far;
1738                 
1739                 if (D3D_fog_mode == 2) {
1740                         glFogf(GL_FOG_START, fog_near);
1741                         glFogf(GL_FOG_END, fog_far);
1742                 }
1743         }
1744 }
1745
1746 void gr_opengl_get_pixel(int x, int y, int *r, int *g, int *b)
1747 {
1748         // Not used.
1749 }
1750
1751 void gr_opengl_set_cull(int cull)
1752 {
1753         if (cull) {
1754                 glEnable (GL_CULL_FACE);
1755                 glFrontFace (GL_CCW);
1756         } else {
1757                 glDisable (GL_CULL_FACE);
1758         }
1759 }
1760
1761 void gr_opengl_filter_set(int filter)
1762 {
1763 }
1764
1765 // cross fade
1766 void gr_opengl_cross_fade(int bmap1, int bmap2, int x1, int y1, int x2, int y2, float pct)
1767 {
1768         gr_set_bitmap(bmap1, GR_ALPHABLEND_FILTER, GR_BITBLT_MODE_NORMAL, 1.0f - pct );
1769         gr_bitmap(x1, y1);
1770
1771         gr_set_bitmap(bmap2, GR_ALPHABLEND_FILTER, GR_BITBLT_MODE_NORMAL, pct );
1772         gr_bitmap(x2, y2);      
1773 }
1774
1775
1776 typedef struct tcache_slot_opengl {
1777         GLuint  texture_handle;
1778         float   u_scale, v_scale;
1779         int     bitmap_id;
1780         int     size;
1781         int     used_this_frame;
1782         int     time_created;
1783         ushort  w,h;
1784
1785         // sections
1786         tcache_slot_opengl      *data_sections[MAX_BMAP_SECTIONS_X][MAX_BMAP_SECTIONS_Y];
1787         tcache_slot_opengl      *parent;
1788         
1789         gr_texture_source       texture_mode;
1790 } tcache_slot_opengl;
1791
1792 static void *Texture_sections = NULL;
1793 static tcache_slot_opengl *Textures = NULL;
1794
1795 static tcache_slot_opengl *GL_bound_texture;
1796
1797 int GL_texture_sections = 0;
1798 int GL_texture_ram = 0;
1799 int GL_frame_count = 0;
1800 int GL_min_texture_width = 0;
1801 int GL_max_texture_width = 0;
1802 int GL_min_texture_height = 0;
1803 int GL_max_texture_height = 0;
1804 int GL_square_textures = 0;
1805 int GL_textures_in = 0;
1806 int GL_textures_in_frame = 0;
1807 int GL_last_bitmap_id = -1;
1808 int GL_last_detail = -1;
1809 int GL_last_bitmap_type = -1;
1810 int GL_last_section_x = -1;
1811 int GL_last_section_y = -1;
1812
1813 int vram_full = 0;
1814
1815 static gr_texture_source GL_current_texture_source = (gr_texture_source) -1;
1816
1817 static void gr_opengl_set_texture_state(gr_texture_source ts)
1818 {
1819         if (ts == TEXTURE_SOURCE_NONE) {
1820                 GL_bound_texture = NULL;
1821                                 
1822                 glBindTexture(GL_TEXTURE_2D, 0);
1823                 gr_tcache_set(-1, -1, NULL, NULL, 0, -1, -1, 0 );
1824         } else if (GL_bound_texture &&
1825                 GL_bound_texture->texture_mode != ts) {
1826                 switch (ts) {
1827                         case TEXTURE_SOURCE_DECAL:
1828                                 glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
1829                                 glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
1830                                 break;
1831                         case TEXTURE_SOURCE_NO_FILTERING:
1832                                 glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
1833                                 glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
1834                                 break;
1835                         default:
1836                                 break;
1837                 }
1838                         
1839                 GL_bound_texture->texture_mode = ts;
1840         }
1841         
1842         GL_current_texture_source = ts;
1843 }
1844
1845 static int opengl_max_tex_size_get()
1846 {
1847         GLint max_texture_size = 0;
1848
1849         glGetIntegerv( GL_MAX_TEXTURE_SIZE, &max_texture_size );
1850         return max_texture_size;
1851 }
1852
1853 static void opengl_tcache_init (int use_sections)
1854 {
1855         int i, idx, s_idx;
1856
1857         // DDOI - FIXME skipped a lot of stuff here
1858         GL_should_preload = 0;
1859
1860         //uint tmp_pl = os_config_read_uint( NULL, NOX("D3DPreloadTextures"), 255 );
1861         uint tmp_pl = 1;
1862
1863         if ( tmp_pl == 0 )      {
1864                 GL_should_preload = 0;
1865         } else if ( tmp_pl == 1 )       {
1866                 GL_should_preload = 1;
1867         } else {
1868                 GL_should_preload = 1;
1869         }
1870
1871         STUB_FUNCTION;
1872
1873         GL_min_texture_width = 16;
1874         GL_min_texture_height = 16;
1875
1876         GL_max_texture_width = opengl_max_tex_size_get();
1877         GL_max_texture_height = opengl_max_tex_size_get();
1878
1879         Textures = (tcache_slot_opengl *)malloc(MAX_BITMAPS*sizeof(tcache_slot_opengl));
1880         if ( !Textures )        {
1881                 exit(1);
1882         }
1883
1884         if(use_sections){
1885                 Texture_sections = (tcache_slot_opengl*)malloc(MAX_BITMAPS * MAX_BMAP_SECTIONS_X * MAX_BMAP_SECTIONS_Y * sizeof(tcache_slot_opengl));
1886                 if(!Texture_sections){
1887                         exit(1);
1888                 }
1889                 memset(Texture_sections, 0, MAX_BITMAPS * MAX_BMAP_SECTIONS_X * MAX_BMAP_SECTIONS_Y * sizeof(tcache_slot_opengl));
1890         }
1891
1892         // Init the texture structures
1893         int section_count = 0;
1894         for( i=0; i<MAX_BITMAPS; i++ )  {
1895                 /*
1896                 Textures[i].vram_texture = NULL;
1897                 Textures[i].vram_texture_surface = NULL;
1898                 */
1899                 Textures[i].texture_handle = 0;
1900
1901                 Textures[i].bitmap_id = -1;
1902                 Textures[i].size = 0;
1903                 Textures[i].used_this_frame = 0;
1904
1905                 Textures[i].parent = NULL;
1906
1907                 // allocate sections
1908                 if(use_sections){
1909                         for(idx=0; idx<MAX_BMAP_SECTIONS_X; idx++){
1910                                 for(s_idx=0; s_idx<MAX_BMAP_SECTIONS_Y; s_idx++){
1911                                         Textures[i].data_sections[idx][s_idx] = &((tcache_slot_opengl*)Texture_sections)[section_count++];
1912                                         Textures[i].data_sections[idx][s_idx]->parent = &Textures[i];
1913                                         /*
1914                                         Textures[i].data_sections[idx][s_idx]->vram_texture = NULL;
1915                                         Textures[i].data_sections[idx][s_idx]->vram_texture_surface = NULL;
1916                                         */
1917                                         Textures[i].data_sections[idx][s_idx]->texture_handle = 0;
1918                                         Textures[i].data_sections[idx][s_idx]->bitmap_id = -1;
1919                                         Textures[i].data_sections[idx][s_idx]->size = 0;
1920                                         Textures[i].data_sections[idx][s_idx]->used_this_frame = 0;
1921                                 }
1922                         }
1923                 } else {
1924                         for(idx=0; idx<MAX_BMAP_SECTIONS_X; idx++){
1925                                 for(s_idx=0; s_idx<MAX_BMAP_SECTIONS_Y; s_idx++){
1926                                         Textures[i].data_sections[idx][s_idx] = NULL;
1927                                 }
1928                         }
1929                 }
1930         }
1931
1932         GL_texture_sections = use_sections;
1933
1934         GL_last_detail = Detail.hardware_textures;
1935         GL_last_bitmap_id = -1;
1936         GL_last_bitmap_type = -1;
1937
1938         GL_last_section_x = -1;
1939         GL_last_section_y = -1;
1940
1941         GL_textures_in = 0;
1942         GL_textures_in_frame = 0;
1943 }
1944
1945 static int opengl_free_texture (tcache_slot_opengl *t);
1946
1947 void opengl_free_texture_with_handle(int handle)
1948 {
1949         for(int i=0; i<MAX_BITMAPS; i++ )  {
1950                 if (Textures[i].bitmap_id == handle) {
1951                         Textures[i].used_this_frame = 0; // this bmp doesn't even exist any longer...
1952                         opengl_free_texture ( &Textures[i] );
1953                 }
1954         }
1955 }
1956
1957 static void opengl_tcache_flush ()
1958 {
1959         int i;
1960
1961         for( i=0; i<MAX_BITMAPS; i++ )  {
1962                 opengl_free_texture ( &Textures[i] );
1963         }
1964         if (GL_textures_in != 0) {
1965                 mprintf(( "WARNING: VRAM is at %d instead of zero after flushing!\n", GL_textures_in ));
1966                 GL_textures_in = 0;
1967         }
1968
1969         GL_last_bitmap_id = -1;
1970         GL_last_section_x = -1;
1971         GL_last_section_y = -1;
1972 }
1973
1974 static void opengl_tcache_cleanup ()
1975 {
1976         opengl_tcache_flush ();
1977
1978         GL_textures_in = 0;
1979         GL_textures_in_frame = 0;
1980
1981         if ( Textures ) {
1982                 free(Textures);
1983                 Textures = NULL;
1984         }
1985
1986         if( Texture_sections != NULL ){
1987                 free(Texture_sections);
1988                 Texture_sections = NULL;
1989         }
1990 }
1991
1992 static void opengl_tcache_frame ()
1993 {
1994         GL_last_bitmap_id = -1;
1995         GL_textures_in_frame = 0;
1996
1997         GL_frame_count++;
1998
1999         /*
2000         int idx, s_idx;
2001         int i;
2002         for( i=0; i<MAX_BITMAPS; i++ )  {
2003                 Textures[i].used_this_frame = 0;
2004
2005                 // data sections
2006                 if(Textures[i].data_sections[0][0] != NULL){
2007                         Assert(GL_texture_sections);
2008                         if(GL_texture_sections){
2009                                 for(idx=0; idx<MAX_BMAP_SECTIONS_X; idx++){
2010                                         for(s_idx=0; s_idx<MAX_BMAP_SECTIONS_Y; s_idx++){
2011                                                 if(Textures[i].data_sections[idx][s_idx] != NULL){
2012                                                         Textures[i].data_sections[idx][s_idx]->used_this_frame = 0;
2013                                                 }
2014                                         }
2015                                 }
2016                         }
2017                 }
2018         }
2019         */
2020
2021         if ( vram_full )        {
2022                 opengl_tcache_flush();
2023                 vram_full = 0;
2024         }
2025 }
2026
2027 static int opengl_free_texture ( tcache_slot_opengl *t )
2028 {
2029         int idx, s_idx;
2030         
2031
2032         // Bitmap changed!!     
2033         if ( t->bitmap_id > -1 )        {
2034                 // if I, or any of my children have been used this frame, bail  
2035                 if(t->used_this_frame == GL_frame_count){
2036                         return 0;
2037                 }
2038                 for(idx=0; idx<MAX_BMAP_SECTIONS_X; idx++){
2039                         for(s_idx=0; s_idx<MAX_BMAP_SECTIONS_Y; s_idx++){
2040                                 if((t->data_sections[idx][s_idx] != NULL) && (t->data_sections[idx][s_idx]->used_this_frame == GL_frame_count)){
2041                                         return 0;
2042                                 }
2043                         }
2044                 }
2045
2046                 // ok, now we know its legal to free everything safely
2047                 t->texture_mode = (gr_texture_source) -1;
2048                 glDeleteTextures (1, &t->texture_handle);
2049                 t->texture_handle = 0;
2050
2051                 if ( GL_last_bitmap_id == t->bitmap_id )       {
2052                         GL_last_bitmap_id = -1;
2053                 }
2054
2055                 // if this guy has children, free them too, since the children
2056                 // actually make up his size
2057                 for(idx=0; idx<MAX_BMAP_SECTIONS_X; idx++){
2058                         for(s_idx=0; s_idx<MAX_BMAP_SECTIONS_Y; s_idx++){
2059                                 if(t->data_sections[idx][s_idx] != NULL){
2060                                         opengl_free_texture(t->data_sections[idx][s_idx]);
2061                                 }
2062                         }
2063                 }
2064
2065                 t->bitmap_id = -1;
2066                 t->used_this_frame = 0;
2067                 GL_textures_in -= t->size;
2068                 t->size = 0;
2069         }
2070
2071         return 1;
2072 }
2073
2074 static void opengl_tcache_get_adjusted_texture_size(int w_in, int h_in, int *w_out, int *h_out)
2075 {
2076         int tex_w, tex_h;
2077         int i;
2078         
2079         // bogus
2080         if((w_out == NULL) ||  (h_out == NULL)){
2081                 return;
2082         }
2083
2084         // starting size
2085         tex_w = w_in;
2086         tex_h = h_in;
2087
2088         // set height and width to a power of 2
2089         for (i=0; i<16; i++ )   {
2090                 if ( (tex_w > (1<<i)) && (tex_w <= (1<<(i+1))) )        {
2091                         tex_w = 1 << (i+1);
2092                         break;
2093                 }
2094         }
2095
2096         for (i=0; i<16; i++ )   {
2097                 if ( (tex_h > (1<<i)) && (tex_h <= (1<<(i+1))) )        {
2098                         tex_h = 1 << (i+1);
2099                         break;
2100                 }
2101         }
2102
2103         // try to keep an 8:1 size ratio
2104         if (tex_w/tex_h > 8)
2105                 tex_h = tex_w/8;
2106         if (tex_h/tex_w > 8)
2107                 tex_w = tex_h/8;
2108
2109         if ( tex_w < GL_min_texture_width ) {
2110                 tex_w = GL_min_texture_width;
2111         } else if ( tex_w > GL_max_texture_width )     {
2112                 tex_w = GL_max_texture_width;
2113         }
2114
2115         if ( tex_h < GL_min_texture_height ) {
2116                 tex_h = GL_min_texture_height;
2117         } else if ( tex_h > GL_max_texture_height )    {
2118                 tex_h = GL_max_texture_height;
2119         }
2120
2121         if ( GL_square_textures) {
2122                 int new_size;
2123                 // Make the both be equal to larger of the two
2124                 new_size = max(tex_w, tex_h);
2125                 tex_w = new_size;
2126                 tex_h = new_size;
2127         }
2128
2129         // store the outgoing size
2130         *w_out = tex_w;
2131         *h_out = tex_h;
2132 }
2133
2134 // data == start of bitmap data
2135 // sx == x offset into bitmap
2136 // sy == y offset into bitmap
2137 // src_w == absolute width of section on source bitmap
2138 // src_h == absolute height of section on source bitmap
2139 // bmap_w == width of source bitmap
2140 // bmap_h == height of source bitmap
2141 // tex_w == width of final texture
2142 // tex_h == height of final texture
2143 static int opengl_create_texture_sub(int bitmap_type, int texture_handle, ushort *data, int sx, int sy, int src_w, int src_h, int bmap_w, int bmap_h, int tex_w, int tex_h, tcache_slot_opengl *t, int reload, int resize, int fail_on_full)
2144 {
2145         int ret_val = 1;
2146         int size;
2147         int i, j;
2148         ubyte *bmp_data = ((ubyte*)data);
2149         ubyte *texmem = NULL, *texmemp;
2150         
2151         // bogus
2152         if((t == NULL) || (bmp_data == NULL)){
2153                 return 0;
2154         }
2155
2156         if ( t->used_this_frame == GL_frame_count )       {
2157                 mprintf(( "ARGHH!!! Texture already used this frame!  Cannot free it!\n" ));
2158                 return 0;
2159         }
2160         if ( !reload )  {
2161                 // gah
2162                 if(!opengl_free_texture(t)){
2163                         return 0;
2164                 }
2165         }
2166
2167         if ( bitmap_type == TCACHE_TYPE_AABITMAP )      {
2168                 t->u_scale = (float)bmap_w / (float)tex_w;
2169                 t->v_scale = (float)bmap_h / (float)tex_h;
2170         } else if(bitmap_type == TCACHE_TYPE_BITMAP_SECTION){
2171                 t->u_scale = (float)src_w / (float)tex_w;
2172                 t->v_scale = (float)src_h / (float)tex_h;
2173         } else {
2174                 t->u_scale = 1.0f;
2175                 t->v_scale = 1.0f;
2176         }
2177
2178         if (!reload) {
2179                 glGenTextures (1, &t->texture_handle);
2180         }
2181         
2182         if (t->texture_handle == 0) {
2183                 nprintf(("Error", "!!DEBUG!! t->texture_handle == 0"));
2184                 return 0;
2185         }
2186                 
2187         GL_bound_texture = t;
2188         
2189         GL_bound_texture->texture_mode = (gr_texture_source) -1;
2190         
2191         glBindTexture (GL_TEXTURE_2D, t->texture_handle);
2192         
2193         glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
2194         glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
2195         glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);
2196
2197         /* this should be set next anyway */    
2198 //      if (GL_current_texture_source != TEXTURE_SOURCE_NONE) {
2199 //              gr_opengl_set_texture_state(GL_current_texture_source);
2200 //      }
2201
2202         size = 0;
2203                 
2204         switch (bitmap_type) {
2205
2206                 case TCACHE_TYPE_AABITMAP:
2207                         {
2208                                 texmem = (ubyte *) malloc (tex_w*tex_h);
2209                                 texmemp = texmem;
2210
2211                                 for (i=0;i<tex_h;i++)
2212                                 {
2213                                         for (j=0;j<tex_w;j++)
2214                                         {
2215                                                 if (i < bmap_h && j < bmap_w) {
2216                                                         *texmemp++ = GL_xlat[bmp_data[i*bmap_w+j]];
2217                                                 } else {
2218                                                         *texmemp++ = 0;
2219                                                 }
2220                                         }
2221                                 }
2222
2223                                 size = tex_w*tex_h;
2224
2225                                 if (!reload) {
2226                                         glTexImage2D (GL_TEXTURE_2D, 0, GL_ALPHA, tex_w, tex_h, 0, GL_ALPHA, GL_UNSIGNED_BYTE, texmem);
2227                                 } else {
2228                                         glTexSubImage2D (GL_TEXTURE_2D, 0, 0, 0, tex_w, tex_h, GL_ALPHA, GL_UNSIGNED_BYTE, texmem);
2229                                 }
2230
2231                                 free (texmem);
2232
2233                                 break;
2234                         }
2235
2236                 case TCACHE_TYPE_BITMAP_SECTION:
2237                         {
2238                                 // if we aren't resizing in any way then we can just use bmp_data directly
2239                                 if ( resize ) {
2240                                         texmem = (ubyte *) malloc (tex_w*tex_h*2);
2241                                         texmemp = texmem;
2242                                 
2243                                         for (i=0;i<tex_h;i++) {
2244                                                 for (j=0;j<tex_w;j++) {
2245                                                         if (i < src_h && j < src_w) {
2246                                                                 *texmemp++ = bmp_data[((i+sy)*bmap_w+(j+sx))*2+0];
2247                                                                 *texmemp++ = bmp_data[((i+sy)*bmap_w+(j+sx))*2+1];
2248                                                         } else {
2249                                                                 *texmemp++ = 0;
2250                                                                 *texmemp++ = 0;
2251                                                         }
2252                                                 }
2253                                         }
2254                                 }
2255                                 
2256                                 size = tex_w*tex_h*2;
2257                                 
2258                                 if (!reload) {
2259                                         glTexImage2D (GL_TEXTURE_2D, 0, GL_RGB5_A1, tex_w, tex_h, 0, GL_BGRA, GL_UNSIGNED_SHORT_1_5_5_5_REV, (resize) ? texmem : bmp_data);
2260                                 } else {
2261                                         glTexSubImage2D (GL_TEXTURE_2D, 0, 0, 0, tex_w, tex_h, GL_BGRA, GL_UNSIGNED_SHORT_1_5_5_5_REV, (resize) ? texmem : bmp_data);
2262                                 }
2263
2264                                 if (texmem != NULL)
2265                                         free(texmem);
2266
2267                                 break;
2268                         }
2269
2270                 default:
2271                         {
2272                                 // if we aren't resizing then we can just use bmp_data directly
2273                                 if ( resize ) {
2274                                         texmem = (ubyte *) malloc (tex_w*tex_h*2);
2275                                         texmemp = texmem;
2276
2277                                         Assert( texmem != NULL );
2278
2279                                         fix u, utmp, v, du, dv;
2280                                 
2281                                         u = v = 0;
2282                                 
2283                                         du = ( (bmap_w-1)*F1_0 ) / tex_w;
2284                                         dv = ( (bmap_h-1)*F1_0 ) / tex_h;
2285                                 
2286                                         for (j=0;j<tex_h;j++) {
2287                                                 utmp = u;
2288                                                 for (i=0;i<tex_w;i++) {
2289                                                         *texmemp++ = bmp_data[(f2i(v)*bmap_w+f2i(utmp))*2+0];
2290                                                         *texmemp++ = bmp_data[(f2i(v)*bmap_w+f2i(utmp))*2+1];
2291                                                         utmp += du;
2292                                                 }
2293                                                 v += dv;
2294                                         }
2295                                 }
2296
2297                                 size = tex_w*tex_h*2;
2298                                 
2299                                 if (!reload) {
2300                                         glTexImage2D (GL_TEXTURE_2D, 0, GL_RGB5_A1, tex_w, tex_h, 0, GL_BGRA, GL_UNSIGNED_SHORT_1_5_5_5_REV, (resize) ? texmem : bmp_data);
2301                                 } else {
2302                                         glTexSubImage2D (GL_TEXTURE_2D, 0, 0, 0, tex_w, tex_h, GL_BGRA, GL_UNSIGNED_SHORT_1_5_5_5_REV, (resize) ? texmem : bmp_data);
2303                                 }
2304
2305                                 if (texmem != NULL)
2306                                         free(texmem);
2307
2308                                 break;
2309                         }
2310
2311                 break;
2312         }
2313         
2314         t->bitmap_id = texture_handle;
2315         t->time_created = GL_frame_count;
2316         t->used_this_frame = 0;
2317         t->size = size;
2318         t->w = (ushort)tex_w;
2319         t->h = (ushort)tex_h;
2320         
2321         GL_textures_in_frame += t->size;
2322         if (!reload) {
2323                 GL_textures_in += t->size;
2324         }
2325
2326         return ret_val;
2327 }
2328
2329 static int opengl_create_texture (int bitmap_handle, int bitmap_type, tcache_slot_opengl *tslot, int fail_on_full)
2330 {
2331         ubyte flags;
2332         bitmap *bmp;
2333         int final_w, final_h;
2334         ubyte bpp = 16;
2335         int reload = 0;
2336         int resize = 0;
2337
2338         // setup texture/bitmap flags
2339         flags = 0;
2340         switch(bitmap_type){
2341                 case TCACHE_TYPE_AABITMAP:
2342                         flags |= BMP_AABITMAP;
2343                         bpp = 8;
2344                         break;
2345                 case TCACHE_TYPE_NORMAL:
2346                         flags |= BMP_TEX_OTHER;
2347                 case TCACHE_TYPE_XPARENT:
2348                         flags |= BMP_TEX_XPARENT;
2349                         break;
2350                 case TCACHE_TYPE_NONDARKENING:
2351                         Int3();
2352                         flags |= BMP_TEX_NONDARK;
2353                         break;
2354         }
2355
2356         // lock the bitmap into the proper format
2357         bmp = bm_lock(bitmap_handle, bpp, flags);
2358         if ( bmp == NULL ) {
2359                 mprintf(("Couldn't lock bitmap %d.\n", bitmap_handle ));
2360                 return 0;
2361         }
2362
2363         int max_w = bmp->w;
2364         int max_h = bmp->h;
2365
2366         
2367            // DDOI - TODO
2368         if ( bitmap_type != TCACHE_TYPE_AABITMAP )      {
2369                 // max_w /= D3D_texture_divider;
2370                 // max_h /= D3D_texture_divider;
2371
2372                 // if we are going to cull the size then we need to force a resize
2373                 if (Detail.hardware_textures < 4) {
2374                         resize = 1;
2375                 }
2376
2377                 // Detail.debris_culling goes from 0 to 4.
2378                 max_w /= (16 >> Detail.hardware_textures);
2379                 max_h /= (16 >> Detail.hardware_textures);
2380         }
2381         
2382
2383         // get final texture size as it will be allocated as a DD surface
2384         opengl_tcache_get_adjusted_texture_size(max_w, max_h, &final_w, &final_h); 
2385
2386         if ( (final_w < 1) || (final_h < 1) ) {
2387                 mprintf(("Bitmap is too small at %dx%d.\n", final_w, final_h));
2388                 return 0;
2389         }
2390
2391         // if we don't have to resize the image (to get power of 2, etc.) then skip that extra work
2392         if ( (max_w != final_w) || (max_h != final_h) ) {
2393                 resize = 1;
2394         }
2395
2396         // if this tcache slot has no bitmap
2397         if ( tslot->bitmap_id < 0) {
2398                 reload = 0;
2399         }
2400         // different bitmap altogether - determine if the new one can use the old one's slot
2401         else if (tslot->bitmap_id != bitmap_handle)     {
2402                 if((final_w == tslot->w) && (final_h == tslot->h)){
2403                         reload = 1;
2404                         //ml_printf("Reloading texture %d\n", bitmap_handle);
2405                 } else {
2406                         reload = 0;
2407                 }
2408         }
2409
2410         // call the helper
2411         int ret_val = opengl_create_texture_sub(bitmap_type, bitmap_handle, (ushort*)bmp->data, 0, 0, bmp->w, bmp->h, bmp->w, bmp->h, final_w, final_h, tslot, reload, resize, fail_on_full);
2412
2413         // unlock the bitmap
2414         bm_unlock(bitmap_handle);
2415
2416         return ret_val;
2417 }
2418
2419 static int opengl_create_texture_sectioned(int bitmap_handle, int bitmap_type, tcache_slot_opengl *tslot, int sx, int sy, int fail_on_full)
2420 {
2421         ubyte flags;
2422         bitmap *bmp;
2423         int final_w, final_h;
2424         int section_x, section_y;
2425         int reload = 0;
2426         int resize = 1;
2427
2428         // setup texture/bitmap flags
2429         Assert(bitmap_type == TCACHE_TYPE_BITMAP_SECTION);
2430         if(bitmap_type != TCACHE_TYPE_BITMAP_SECTION){
2431                 bitmap_type = TCACHE_TYPE_BITMAP_SECTION;
2432         }
2433         flags = BMP_TEX_XPARENT;
2434
2435         // lock the bitmap in the proper format
2436         bmp = bm_lock(bitmap_handle, 16, flags);
2437         if ( bmp == NULL ) {
2438                 mprintf(("Couldn't lock bitmap %d.\n", bitmap_handle ));
2439                 return 0;
2440         }
2441         // determine the width and height of this section
2442         bm_get_section_size(bitmap_handle, sx, sy, &section_x, &section_y);
2443
2444         // get final texture size as it will be allocated as an opengl texture
2445         opengl_tcache_get_adjusted_texture_size(section_x, section_y, &final_w, &final_h);
2446
2447         if ( (final_w < 1) || (final_h < 1) ) {
2448                 mprintf(("Bitmap is too small at %dx%d.\n", final_w, final_h));
2449                 return 0;
2450         }
2451
2452         // if we don't have to resize the image (to get power of 2, etc.) then skip that extra work
2453         if ( (bmp->sections.num_x == 1) && (bmp->sections.num_y == 1) && (section_x == final_w) && (section_y == final_h) ) {
2454                 resize = 0;
2455         }
2456
2457         // if this tcache slot has no bitmap
2458         if ( tslot->bitmap_id < 0) {
2459                 reload = 0;
2460         }
2461         // different bitmap altogether - determine if the new one can use the old one's slot
2462         else if (tslot->bitmap_id != bitmap_handle)     {
2463                 if((final_w == tslot->w) && (final_h == tslot->h)){
2464                         reload = 1;
2465                 } else {
2466                         reload = 0;
2467                 }
2468         }
2469
2470         // call the helper
2471         int ret_val = opengl_create_texture_sub(bitmap_type, bitmap_handle, (ushort*)bmp->data, bmp->sections.sx[sx], bmp->sections.sy[sy], section_x, section_y, bmp->w, bmp->h, final_w, final_h, tslot, reload, resize, fail_on_full);
2472
2473         // unlock the bitmap
2474         bm_unlock(bitmap_handle);
2475
2476         return ret_val;
2477 }
2478
2479                 
2480 extern int bm_get_cache_slot( int bitmap_id, int separate_ani_frames );
2481 static int gr_opengl_tcache_set(int bitmap_id, int bitmap_type, float *u_scale, float *v_scale, int fail_on_full = 0, int sx = -1, int sy = -1, int force = 0)
2482 {
2483         bitmap *bmp = NULL;
2484
2485         int idx, s_idx;
2486         int ret_val = 1;
2487
2488         if (bitmap_id < 0)
2489         {
2490                 GL_last_bitmap_id = -1;
2491                 return 0;
2492         }
2493
2494         if ( GL_last_detail != Detail.hardware_textures )      {
2495                 GL_last_detail = Detail.hardware_textures;
2496                 opengl_tcache_flush();
2497         }
2498
2499         if (vram_full) {
2500                 return 0;
2501         }
2502
2503         int n = bm_get_cache_slot (bitmap_id, 1);
2504         tcache_slot_opengl *t = &Textures[n];
2505
2506         if ( (GL_last_bitmap_id == bitmap_id) && (GL_last_bitmap_type==bitmap_type) && (t->bitmap_id == bitmap_id) && (GL_last_section_x == sx) && (GL_last_section_y == sy))       {
2507                 t->used_this_frame = GL_frame_count;
2508
2509                 // mark all children as used
2510                 if(GL_texture_sections){
2511                         for(idx=0; idx<MAX_BMAP_SECTIONS_X; idx++){
2512                                 for(s_idx=0; s_idx<MAX_BMAP_SECTIONS_Y; s_idx++){
2513                                         if(t->data_sections[idx][s_idx] != NULL){
2514                                                 t->data_sections[idx][s_idx]->used_this_frame = GL_frame_count;
2515                                         }
2516                                 }
2517                         }
2518                 }
2519
2520                 *u_scale = t->u_scale;
2521                 *v_scale = t->v_scale;
2522                 return 1;
2523         }
2524
2525         if (bitmap_type == TCACHE_TYPE_BITMAP_SECTION){
2526                 Assert((sx >= 0) && (sy >= 0) && (sx < MAX_BMAP_SECTIONS_X) && (sy < MAX_BMAP_SECTIONS_Y));
2527                 if(!((sx >= 0) && (sy >= 0) && (sx < MAX_BMAP_SECTIONS_X) && (sy < MAX_BMAP_SECTIONS_Y))){
2528                         return 0;
2529                 }
2530
2531                 ret_val = 1;
2532
2533                 // if the texture sections haven't been created yet
2534                 if((t->bitmap_id < 0) || (t->bitmap_id != bitmap_id)){
2535
2536                         // lock the bitmap in the proper format
2537                         bmp = bm_lock(bitmap_id, 16, BMP_TEX_XPARENT);
2538                         bm_unlock(bitmap_id);
2539
2540                         // now lets do something for each texture
2541
2542                         for(idx=0; idx<bmp->sections.num_x; idx++){
2543                                 for(s_idx=0; s_idx<bmp->sections.num_y; s_idx++){
2544                                         // hmm. i'd rather we didn't have to do it this way...
2545                                         if(!opengl_create_texture_sectioned(bitmap_id, bitmap_type, t->data_sections[idx][s_idx], idx, s_idx, fail_on_full)){
2546                                                 ret_val = 0;
2547                                         }
2548
2549                                         // not used this frame
2550                                         t->data_sections[idx][s_idx]->used_this_frame = 0;
2551                                 }
2552                         }
2553
2554                         // zero out pretty much everything in the parent struct since he's just the root
2555                         t->bitmap_id = bitmap_id;
2556                         t->texture_handle = 0;
2557                         t->time_created = t->data_sections[sx][sy]->time_created;
2558                         t->used_this_frame = 0;
2559                         /*
2560                         t->vram_texture = NULL;
2561                         t->vram_texture_surface = NULL
2562                         */
2563                 }
2564
2565                 // argh. we failed to upload. free anything we can
2566                 if(!ret_val){
2567                         opengl_free_texture(t);
2568                 }
2569                 // swap in the texture we want
2570                 else {
2571                         t = t->data_sections[sx][sy];
2572                 }
2573         }
2574         // all other "normal" textures
2575         else if((bitmap_id < 0) || (bitmap_id != t->bitmap_id)){
2576                 ret_val = opengl_create_texture( bitmap_id, bitmap_type, t, fail_on_full );
2577         }
2578
2579         // everything went ok
2580         if(ret_val && (t->texture_handle) && !vram_full){
2581                 *u_scale = t->u_scale;
2582                 *v_scale = t->v_scale;
2583
2584                 GL_bound_texture = t;
2585                 
2586                 glBindTexture (GL_TEXTURE_2D, t->texture_handle );
2587
2588                 /* this should be set next anyway */
2589 //              if (GL_current_texture_source != TEXTURE_SOURCE_NONE) {
2590 //                      gr_opengl_set_texture_state(GL_current_texture_source);
2591 //              }
2592                 
2593                 GL_last_bitmap_id = t->bitmap_id;
2594                 GL_last_bitmap_type = bitmap_type;
2595                 GL_last_section_x = sx;
2596                 GL_last_section_y = sy;
2597
2598                 t->used_this_frame = GL_frame_count;
2599         }
2600         // gah
2601         else {
2602                 GL_last_bitmap_id = -1;
2603                 GL_last_bitmap_type = -1;
2604
2605                 GL_last_section_x = -1;
2606                 GL_last_section_y = -1;
2607
2608                 GL_bound_texture = NULL;
2609                 
2610                 glBindTexture (GL_TEXTURE_2D, 0);       // test - DDOI
2611                 return 0;
2612         }
2613
2614         return 1;
2615 }
2616
2617 void gr_opengl_set_clear_color(int r, int g, int b)
2618 {
2619         gr_init_color (&gr_screen.current_clear_color, r, g, b);
2620 }
2621
2622 void gr_opengl_flash(int r, int g, int b)
2623 {
2624         CAP(r,0,255);
2625         CAP(g,0,255);
2626         CAP(b,0,255);
2627         
2628         if ( r || g || b ) {
2629                 gr_opengl_set_state( TEXTURE_SOURCE_NONE, ALPHA_BLEND_ALPHA_ADDITIVE, ZBUFFER_TYPE_NONE );
2630                 
2631                 float x1, x2, y1, y2;
2632                 x1 = i2fl(gr_screen.clip_left+gr_screen.offset_x);
2633                 y1 = i2fl(gr_screen.clip_top+gr_screen.offset_y);
2634                 x2 = i2fl(gr_screen.clip_right+gr_screen.offset_x);
2635                 y2 = i2fl(gr_screen.clip_bottom+gr_screen.offset_y);
2636                 
2637                 glColor4ub(r, g, b, 255);
2638                 glBegin (GL_QUADS);
2639                   glVertex3f (x1, y2, -0.99);
2640
2641                   glVertex3f (x2, y2, -0.99);
2642
2643                   glVertex3f (x2, y1, -0.99);
2644
2645                   glVertex3f (x1, y1, -0.99);
2646                 glEnd ();         
2647         }
2648 }
2649
2650 int gr_opengl_zbuffer_get()
2651 {
2652         if ( !gr_global_zbuffering )    {
2653                 return GR_ZBUFF_NONE;
2654         }
2655         return gr_zbuffering_mode;
2656 }
2657
2658 int gr_opengl_zbuffer_set(int mode)
2659 {
2660         int tmp = gr_zbuffering_mode;
2661
2662         gr_zbuffering_mode = mode;
2663
2664         if (gr_zbuffering_mode == GR_ZBUFF_NONE )      {
2665                 gr_zbuffering = 0;
2666         } else {
2667                 gr_zbuffering = 1;
2668         }
2669         return tmp;
2670 }
2671
2672 void gr_opengl_zbuffer_clear(int mode)
2673 {
2674         if (mode) {
2675                 gr_zbuffering = 1;
2676                 gr_zbuffering_mode = GR_ZBUFF_FULL;
2677                 gr_global_zbuffering = 1;
2678                 
2679                 gr_opengl_set_state( TEXTURE_SOURCE_NONE, ALPHA_BLEND_NONE, ZBUFFER_TYPE_FULL );
2680                 glClear ( GL_DEPTH_BUFFER_BIT );
2681         } else {
2682                 gr_zbuffering = 0;
2683                 gr_zbuffering_mode = GR_ZBUFF_NONE;
2684                 gr_global_zbuffering = 0;
2685         }
2686 }
2687
2688 void gr_opengl_set_gamma(float gamma)
2689 {
2690         Gr_gamma = gamma;
2691         Gr_gamma_int = int (Gr_gamma*10);
2692
2693         // Create the Gamma lookup table
2694         int i;
2695         for (i=0;i<256; i++) {
2696                 int v = fl2i(pow(i2fl(i)/255.0f, 1.0f/Gr_gamma)*255.0f);
2697                 if ( v > 255 ) {
2698                         v = 255;
2699                 } else if ( v < 0 )     {
2700                         v = 0;
2701                 }
2702                 Gr_gamma_lookup[i] = v;
2703         }
2704
2705         // set the alpha gamma settings (for fonts)
2706         for (i=0; i<16; i++) {
2707                 GL_xlat[i] = (ubyte)Gr_gamma_lookup[(i*255)/15];
2708         }
2709
2710         GL_xlat[15] = GL_xlat[1];
2711
2712         for (; i<256; i++) {
2713                 GL_xlat[i] = GL_xlat[0];
2714         }
2715
2716         // Flush any existing textures
2717         opengl_tcache_flush();
2718 }
2719
2720 void gr_opengl_fade_in(int instantaneous)
2721 {
2722         // Empty - DDOI
2723 }
2724
2725 void gr_opengl_fade_out(int instantaneous)
2726 {
2727         // Empty - DDOI
2728 }
2729
2730 void gr_opengl_get_region(int front, int w, int h, ubyte *data)
2731 {
2732         if (front) {
2733                 glReadBuffer(GL_FRONT);
2734         } else {
2735                 glReadBuffer(GL_BACK);
2736         }
2737         
2738         gr_opengl_set_state(TEXTURE_SOURCE_NO_FILTERING, ALPHA_BLEND_NONE, ZBUFFER_TYPE_NONE);
2739         
2740         glPixelStorei(GL_UNPACK_ROW_LENGTH, gr_screen.max_w);
2741         
2742         if (gr_screen.bits_per_pixel == 15) {
2743                 glReadPixels(0, gr_screen.max_h-h-1, w, h, GL_BGRA, GL_UNSIGNED_SHORT_1_5_5_5_REV, data);
2744         } else if (gr_screen.bits_per_pixel == 32) {
2745                 glReadPixels(0, gr_screen.max_h-h-1, w, h, GL_RGBA, GL_UNSIGNED_BYTE, data);
2746         }
2747         
2748         glPixelStorei(GL_UNPACK_ROW_LENGTH, 0);
2749 }
2750
2751 void gr_opengl_save_mouse_area(int x, int y, int w, int h)
2752 {
2753         Gr_opengl_mouse_saved_x1 = x;
2754         Gr_opengl_mouse_saved_y1 = y;
2755         Gr_opengl_mouse_saved_x2 = x+w-1;
2756         Gr_opengl_mouse_saved_y2 = y+h-1;
2757         
2758         CLAMP(Gr_opengl_mouse_saved_x1, gr_screen.clip_left, gr_screen.clip_right );
2759         CLAMP(Gr_opengl_mouse_saved_x2, gr_screen.clip_left, gr_screen.clip_right );
2760         CLAMP(Gr_opengl_mouse_saved_y1, gr_screen.clip_top, gr_screen.clip_bottom );
2761         CLAMP(Gr_opengl_mouse_saved_y2, gr_screen.clip_top, gr_screen.clip_bottom );
2762         
2763         Gr_opengl_mouse_saved_w = Gr_opengl_mouse_saved_x2 - Gr_opengl_mouse_saved_x1 + 1;
2764         Gr_opengl_mouse_saved_h = Gr_opengl_mouse_saved_y2 - Gr_opengl_mouse_saved_y1 + 1;
2765
2766         if ( Gr_opengl_mouse_saved_w < 1 ) return;
2767         if ( Gr_opengl_mouse_saved_h < 1 ) return;
2768         
2769         Assert( (Gr_opengl_mouse_saved_w*Gr_opengl_mouse_saved_h) <= MAX_SAVE_SIZE );
2770
2771         gr_opengl_set_state(TEXTURE_SOURCE_NO_FILTERING, ALPHA_BLEND_NONE, ZBUFFER_TYPE_NONE);
2772         
2773         glReadBuffer(GL_BACK);
2774         glReadPixels(x, gr_screen.max_h-y-1-h, w, h, GL_BGRA, GL_UNSIGNED_SHORT_1_5_5_5_REV, Gr_opengl_mouse_saved_data);
2775         
2776         Gr_opengl_mouse_saved = 1;
2777 }
2778
2779 int gr_opengl_save_screen()
2780 {
2781         gr_reset_clip();
2782
2783         if ( Gr_saved_screen )  {
2784                 mprintf(( "Screen alread saved!\n" ));
2785                 return -1;
2786         }
2787
2788         Gr_saved_screen = (char*)malloc( gr_screen.max_w * gr_screen.max_h * gr_screen.bytes_per_pixel );
2789         if (!Gr_saved_screen) {
2790                 mprintf(( "Couldn't get memory for saved screen!\n" ));
2791                 return -1;
2792         }
2793
2794         char *Gr_saved_screen_tmp = (char*)malloc( gr_screen.max_w * gr_screen.max_h * gr_screen.bytes_per_pixel );
2795         if (!Gr_saved_screen_tmp) {
2796                 mprintf(( "Couldn't get memory for temporary saved screen!\n" ));
2797                 return -1;
2798         }
2799         
2800         gr_opengl_set_state(TEXTURE_SOURCE_NO_FILTERING, ALPHA_BLEND_NONE, ZBUFFER_TYPE_NONE);
2801         
2802         glReadBuffer(GL_FRONT);
2803         glReadPixels(0, 0, gr_screen.max_w, gr_screen.max_h, GL_BGRA, GL_UNSIGNED_SHORT_1_5_5_5_REV, Gr_saved_screen_tmp);
2804         
2805         ubyte *sptr, *dptr;
2806         
2807         sptr = (ubyte *)&Gr_saved_screen_tmp[gr_screen.max_w*gr_screen.max_h*2];
2808         dptr = (ubyte *)Gr_saved_screen;
2809         for (int j = 0; j < gr_screen.max_h; j++) {
2810                 sptr -= gr_screen.max_w*2;
2811                 memcpy(dptr, sptr, gr_screen.max_w*2);
2812                 dptr += gr_screen.max_w*2;
2813         }
2814         
2815         free(Gr_saved_screen_tmp);
2816         
2817         if (Gr_opengl_mouse_saved) {
2818                 sptr = (ubyte *)Gr_opengl_mouse_saved_data;
2819                 dptr = (ubyte *)&Gr_saved_screen[2*(Gr_opengl_mouse_saved_x1+(Gr_opengl_mouse_saved_y2)*gr_screen.max_w)];
2820                 for (int i = 0; i < Gr_opengl_mouse_saved_h; i++) {
2821                         memcpy(dptr, sptr, Gr_opengl_mouse_saved_w*2);
2822                 
2823                         sptr += 32*2;
2824                         dptr -= gr_screen.max_w*2;
2825                 }
2826         }
2827
2828         // this leaks texture handles, and the opengl doesn't currently 
2829         // perform some sort of garbage collection, so a hack was added
2830         // to bmpman to make it free textures when released
2831         Gr_saved_screen_bitmap = bm_create(16, gr_screen.max_w, gr_screen.max_h, Gr_saved_screen, 0);
2832         
2833         return Gr_saved_screen_bitmap;
2834 }
2835
2836 void gr_opengl_restore_screen(int id)
2837 {
2838         gr_reset_clip();
2839         
2840         if ( !Gr_saved_screen ) {
2841                 gr_clear();
2842                 return;
2843         }
2844
2845         gr_opengl_set_state(TEXTURE_SOURCE_NO_FILTERING, ALPHA_BLEND_NONE, ZBUFFER_TYPE_NONE);
2846         
2847         gr_set_bitmap(Gr_saved_screen_bitmap, GR_ALPHABLEND_NONE, GR_BITBLT_MODE_NORMAL, 1.0f, -1, -1);
2848         gr_bitmap(0, 0);                
2849 }
2850
2851 void gr_opengl_free_screen(int id)
2852 {
2853         bm_release(Gr_saved_screen_bitmap);
2854         
2855         if ( Gr_saved_screen )  {
2856                 free( Gr_saved_screen );
2857                 Gr_saved_screen = NULL;
2858         }
2859 }
2860
2861 void gr_opengl_dump_frame_start(int first_frame, int frames_between_dumps)
2862 {
2863         STUB_FUNCTION;
2864 }
2865
2866 void gr_opengl_dump_frame_stop()
2867 {
2868         STUB_FUNCTION;
2869 }
2870
2871 void gr_opengl_dump_frame()
2872 {
2873         STUB_FUNCTION;
2874 }
2875
2876 uint gr_opengl_lock()
2877 {
2878         STUB_FUNCTION;
2879         
2880         return 1;
2881 }
2882         
2883 void gr_opengl_unlock()
2884 {
2885 }
2886
2887 void opengl_zbias(int bias)
2888 {
2889         if (bias) {
2890                 glEnable(GL_POLYGON_OFFSET_FILL);
2891                 glPolygonOffset(0.0, -bias);
2892         } else {
2893                 glDisable(GL_POLYGON_OFFSET_FILL);
2894         }
2895 }
2896                 
2897 extern const char *Osreg_title;
2898 void gr_opengl_init()
2899 {
2900         if ( Inited )   {
2901                 gr_opengl_cleanup();
2902                 Inited = 0;
2903         }
2904
2905         mprintf(( "Initializing opengl graphics device...\n" ));
2906         Inited = 1;
2907
2908 #ifdef PLAT_UNIX        
2909         if (SDL_InitSubSystem (SDL_INIT_VIDEO) < 0)
2910         {
2911                 fprintf (stderr, "Couldn't init SDL: %s", SDL_GetError());
2912                 exit (1);
2913         }
2914
2915         SDL_GL_SetAttribute(SDL_GL_RED_SIZE, 5);
2916         SDL_GL_SetAttribute(SDL_GL_GREEN_SIZE, 5);
2917         SDL_GL_SetAttribute(SDL_GL_BLUE_SIZE, 5);
2918         SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 16);
2919         SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
2920         
2921         int flags = SDL_OPENGL;
2922         
2923         if (!Cmdline_window && ( (os_config_read_uint( NULL, "Fullscreen", 1 ) == 1) || Cmdline_fullscreen ))
2924                 flags |= SDL_FULLSCREEN;
2925
2926         // grab mouse/key unless told otherwise, ignore when we are going fullscreen
2927         if ( !((flags & SDL_FULLSCREEN) || Cmdline_no_grab) ) {
2928                 SDL_WM_GrabInput(SDL_GRAB_ON);
2929         }
2930
2931         FSAA = os_config_read_uint( NULL, "FSAA", 1 );
2932         if ( FSAA ) {
2933             SDL_GL_SetAttribute( SDL_GL_MULTISAMPLEBUFFERS, 1 );
2934             SDL_GL_SetAttribute( SDL_GL_MULTISAMPLESAMPLES, FSAA );
2935         }
2936         
2937         if (SDL_SetVideoMode (gr_screen.max_w, gr_screen.max_h,0,flags) == NULL)
2938         {
2939             mprintf(( "Couldn't set FSAA video mode: %s\n", SDL_GetError () ));
2940             SDL_GL_SetAttribute( SDL_GL_MULTISAMPLEBUFFERS, 0 );
2941             SDL_GL_SetAttribute( SDL_GL_MULTISAMPLESAMPLES, 0 );
2942                 
2943             if (SDL_SetVideoMode (gr_screen.max_w, gr_screen.max_h,0,flags) == NULL)
2944             {
2945                     fprintf (stderr, "Couldn't set video mode: %s\n", SDL_GetError ());
2946                     exit (1);
2947             }
2948         }
2949
2950         mprintf(( "Screen BPP: %d\n", SDL_GetVideoSurface()->format->BitsPerPixel ));
2951         mprintf(( "\n" ));
2952         mprintf(( "Vendor     : %s\n", glGetString(GL_VENDOR) ));
2953         mprintf(( "Renderer   : %s\n", glGetString(GL_RENDERER) ));
2954         mprintf(( "Version    : %s\n", glGetString(GL_VERSION) ));
2955
2956 #ifndef NDEBUG
2957         // print out extensions - taken from FS2_Open (credits: phreak, taylor)
2958         mprintf(( "Extensions : \n"));
2959
2960         static const char *OGL_extensions = (const char*)glGetString(GL_EXTENSIONS);
2961
2962         // we use the "+1" here to have an extra NULL char on the end (with the memset())
2963         // this is to fix memory errors when the last char in extlist is the same as the token
2964         // we are looking for and ultra evil strtok() may still return non-NULL at EOS
2965         char *extlist = (char*)malloc(strlen(OGL_extensions) + 1);
2966         memset(extlist, 0, strlen(OGL_extensions) + 1);
2967
2968         if (extlist != NULL) {
2969                 memcpy(extlist, OGL_extensions, strlen(OGL_extensions));
2970
2971                 char *curext = strtok(extlist, " ");
2972
2973                 while (curext) {
2974                         mprintf(( "     %s\n", curext ));
2975                         curext = strtok(NULL, " ");
2976                 }
2977
2978                 free(extlist);
2979                 extlist = NULL;
2980         }
2981
2982         mprintf(( "\n" ));
2983 #endif
2984         
2985         int value;
2986         int rgb_size[3];
2987         int bpp = 15;
2988         rgb_size[0]=5;
2989         rgb_size[1]=5;
2990         rgb_size[2]=5;
2991
2992         SDL_GL_GetAttribute( SDL_GL_RED_SIZE, &value );
2993         mprintf(( "SDL_GL_RED_SIZE: requested %d, got %d\n", rgb_size[0],value ));
2994         SDL_GL_GetAttribute( SDL_GL_GREEN_SIZE, &value );
2995         mprintf(( "SDL_GL_GREEN_SIZE: requested %d, got %d\n", rgb_size[1],value ));
2996         SDL_GL_GetAttribute( SDL_GL_BLUE_SIZE, &value );
2997         mprintf(( "SDL_GL_BLUE_SIZE: requested %d, got %d\n", rgb_size[2],value ));
2998         SDL_GL_GetAttribute( SDL_GL_DEPTH_SIZE, &value );
2999         mprintf(( "SDL_GL_DEPTH_SIZE: requested %d, got %d\n", bpp, value ));
3000         SDL_GL_GetAttribute( SDL_GL_DOUBLEBUFFER, &value );
3001         mprintf(( "SDL_GL_DOUBLEBUFFER: requested 1, got %d\n", value ));
3002
3003         if ( FSAA ) {
3004                 SDL_GL_GetAttribute( SDL_GL_MULTISAMPLEBUFFERS, &value );
3005                 mprintf(( "SDL_GL_MULTISAMPLEBUFFERS: requested 1, got %d\n", value ));
3006                 SDL_GL_GetAttribute( SDL_GL_MULTISAMPLESAMPLES, &value );
3007                 mprintf(( "SDL_GL_MULTISAMPLESAMPLES: requested %d, got %d\n", FSAA, value ));
3008         }
3009
3010         SDL_ShowCursor(0);
3011         SDL_WM_SetCaption (Osreg_title, NULL);
3012         
3013         /* might as well put this here */
3014         SDL_EnableKeyRepeat(SDL_DEFAULT_REPEAT_DELAY, SDL_DEFAULT_REPEAT_INTERVAL);
3015 #endif
3016
3017         GL_use_luminance_alpha = os_config_read_uint(NOX("OpenGL"), NOX("UseLuminanceAlpha"), 0);
3018
3019         glViewport(0, 0, gr_screen.max_w, gr_screen.max_h);
3020
3021         glMatrixMode(GL_PROJECTION);
3022         glLoadIdentity();
3023         glOrtho(0, gr_screen.max_w, gr_screen.max_h, 0, 0.0, 1.0);
3024         glMatrixMode(GL_MODELVIEW);
3025         glLoadIdentity();
3026         
3027         glShadeModel(GL_SMOOTH);
3028         glEnable(GL_DITHER);
3029         glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST);
3030         glHint(GL_FOG_HINT, GL_NICEST);
3031                 
3032         glEnable(GL_DEPTH_TEST);
3033         glEnable(GL_BLEND);
3034         
3035         glEnable(GL_TEXTURE_2D);
3036         
3037         glDepthRange(0.0, 1.0);
3038         
3039         glPixelStorei(GL_PACK_ALIGNMENT, 1);
3040         glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
3041         
3042         D3D_32bit = 1;              // grd3d.cpp
3043         extern int D3D_enabled;
3044         D3D_enabled = 1;
3045         /* 
3046           TODO: set fog_mode to 1 if EXT_secondary_color found and wanted 
3047           1 = use secondary color ext
3048           2 = use opengl linear fog
3049          */
3050         D3D_fog_mode = 2;          // grd3d.cpp
3051
3052         glFlush();
3053         
3054         Bm_pixel_format = BM_PIXEL_FORMAT_ARGB;
3055         Gr_bitmap_poly = 1;
3056         
3057         switch( bpp )   {
3058         case 15:
3059                 gr_screen.bits_per_pixel = 15;
3060                 gr_screen.bytes_per_pixel = 2;
3061                 
3062                 Gr_red.bits = 5;
3063                 Gr_red.shift = 10;
3064                 Gr_red.scale = 8;
3065                 Gr_red.mask = 0x7C00;
3066
3067                 Gr_green.bits = 5;
3068                 Gr_green.shift = 5;
3069                 Gr_green.scale = 8;
3070                 Gr_green.mask = 0x3E0;
3071
3072                 Gr_blue.bits = 5;
3073                 Gr_blue.shift = 0;
3074                 Gr_blue.scale = 8;
3075                 Gr_blue.mask = 0x1F;
3076
3077                 break;
3078
3079         case 16:
3080                 gr_screen.bits_per_pixel = 16;
3081                 gr_screen.bytes_per_pixel = 2;
3082                 
3083                 Gr_red.bits = 5;
3084                 Gr_red.shift = 11;
3085                 Gr_red.scale = 8;
3086                 Gr_red.mask = 0xF800;
3087
3088                 Gr_green.bits = 6;
3089                 Gr_green.shift = 5;
3090                 Gr_green.scale = 4;
3091                 Gr_green.mask = 0x7E0;
3092
3093                 Gr_blue.bits = 5;
3094                 Gr_blue.shift = 0;
3095                 Gr_blue.scale = 8;
3096                 Gr_blue.mask = 0x1F;
3097
3098                 break;
3099
3100         case 32:
3101                 gr_screen.bits_per_pixel = 32;
3102                 gr_screen.bytes_per_pixel = 4;
3103                 
3104                 Gr_red.bits = 8;
3105                 Gr_red.shift = 16;
3106                 Gr_red.scale = 1;
3107                 Gr_red.mask = 0xff0000;
3108
3109                 Gr_green.bits = 8;
3110                 Gr_green.shift = 8;
3111                 Gr_green.scale = 1;
3112                 Gr_green.mask = 0xff00;
3113
3114                 Gr_blue.bits = 8;
3115                 Gr_blue.shift = 0;
3116                 Gr_blue.scale = 1;
3117                 Gr_blue.mask = 0xff;
3118
3119                 break;
3120
3121         default:
3122                 Int3(); // Illegal bpp
3123         }
3124
3125         // DDOI - set these so no one else does!
3126         Gr_t_red.mask = Gr_red.mask;
3127         Gr_t_red.shift = Gr_red.shift;
3128         Gr_t_red.scale = Gr_red.scale;
3129
3130         Gr_t_green.mask = Gr_green.mask;
3131         Gr_t_green.shift = Gr_green.shift;
3132         Gr_t_green.scale = Gr_green.scale;
3133         
3134         Gr_t_blue.mask = Gr_blue.mask;
3135         Gr_t_blue.shift = Gr_blue.shift;
3136         Gr_t_blue.scale = Gr_blue.scale;
3137         
3138         Gr_t_alpha.mask = 0x8000;
3139         Gr_t_alpha.scale = 255;
3140         Gr_t_alpha.shift = 15;
3141
3142         Gr_ta_red.mask = 0x0f00;
3143         Gr_ta_red.shift = 8;
3144         Gr_ta_red.scale = 16;
3145
3146         Gr_ta_green.mask = 0x00f0;
3147         Gr_ta_green.shift = 4;
3148         Gr_ta_green.scale = 16;
3149         
3150         Gr_ta_blue.mask = 0x000f;
3151         Gr_ta_blue.shift = 0;
3152         Gr_ta_blue.scale = 16;
3153
3154         Gr_ta_alpha.mask = 0xf000;
3155         Gr_ta_alpha.shift = 12;
3156         Gr_ta_alpha.scale = 16;
3157
3158
3159         opengl_tcache_init (1);
3160         gr_opengl_clear();
3161
3162         Gr_current_red = &Gr_red;
3163         Gr_current_blue = &Gr_blue;
3164         Gr_current_green = &Gr_green;
3165         Gr_current_alpha = &Gr_alpha;
3166
3167         gr_screen.gf_flip = gr_opengl_flip;
3168         gr_screen.gf_flip_window = gr_opengl_flip_window;
3169         gr_screen.gf_set_clip = gr_opengl_set_clip;
3170         gr_screen.gf_reset_clip = gr_opengl_reset_clip;
3171         gr_screen.gf_set_font = grx_set_font;
3172         
3173         gr_screen.gf_set_color = gr_opengl_set_color;
3174         gr_screen.gf_set_bitmap = gr_opengl_set_bitmap;
3175         gr_screen.gf_create_shader = gr_opengl_create_shader;
3176         gr_screen.gf_set_shader = gr_opengl_set_shader;
3177         gr_screen.gf_clear = gr_opengl_clear;
3178         // gr_screen.gf_bitmap = gr_opengl_bitmap;
3179         // gr_screen.gf_bitmap_ex = gr_opengl_bitmap_ex;
3180         gr_screen.gf_aabitmap = gr_opengl_aabitmap;
3181         gr_screen.gf_aabitmap_ex = gr_opengl_aabitmap_ex;
3182         
3183         gr_screen.gf_rect = gr_opengl_rect;
3184         gr_screen.gf_shade = gr_opengl_shade;
3185         gr_screen.gf_string = gr_opengl_string;
3186         gr_screen.gf_circle = gr_opengl_circle;
3187
3188         gr_screen.gf_line = gr_opengl_line;
3189         gr_screen.gf_aaline = gr_opengl_aaline;
3190         gr_screen.gf_pixel = gr_opengl_pixel;
3191         gr_screen.gf_scaler = gr_opengl_scaler;
3192         gr_screen.gf_tmapper = gr_opengl_tmapper;
3193
3194         gr_screen.gf_gradient = gr_opengl_gradient;
3195
3196         gr_screen.gf_set_palette = gr_opengl_set_palette;
3197         gr_screen.gf_get_color = gr_opengl_get_color;
3198         gr_screen.gf_init_color = gr_opengl_init_color;
3199         gr_screen.gf_init_alphacolor = gr_opengl_init_alphacolor;
3200         gr_screen.gf_set_color_fast = gr_opengl_set_color_fast;
3201         gr_screen.gf_print_screen = gr_opengl_print_screen;
3202
3203         gr_screen.gf_fade_in = gr_opengl_fade_in;
3204         gr_screen.gf_fade_out = gr_opengl_fade_out;
3205         gr_screen.gf_flash = gr_opengl_flash;
3206         
3207         gr_screen.gf_zbuffer_get = gr_opengl_zbuffer_get;
3208         gr_screen.gf_zbuffer_set = gr_opengl_zbuffer_set;
3209         gr_screen.gf_zbuffer_clear = gr_opengl_zbuffer_clear;
3210         
3211         gr_screen.gf_save_screen = gr_opengl_save_screen;
3212         gr_screen.gf_restore_screen = gr_opengl_restore_screen;
3213         gr_screen.gf_free_screen = gr_opengl_free_screen;
3214         
3215         gr_screen.gf_dump_frame_start = gr_opengl_dump_frame_start;
3216         gr_screen.gf_dump_frame_stop = gr_opengl_dump_frame_stop;
3217         gr_screen.gf_dump_frame = gr_opengl_dump_frame;
3218         
3219         gr_screen.gf_set_gamma = gr_opengl_set_gamma;
3220         
3221         gr_screen.gf_lock = gr_opengl_lock;
3222         gr_screen.gf_unlock = gr_opengl_unlock;
3223         
3224         gr_screen.gf_fog_set = gr_opengl_fog_set;       
3225
3226         gr_screen.gf_get_region = gr_opengl_get_region;
3227
3228         gr_screen.gf_get_pixel = gr_opengl_get_pixel;
3229
3230         gr_screen.gf_set_cull = gr_opengl_set_cull;
3231
3232         gr_screen.gf_cross_fade = gr_opengl_cross_fade;
3233
3234         gr_screen.gf_filter_set = gr_opengl_filter_set;
3235
3236         gr_screen.gf_tcache_set = gr_opengl_tcache_set;
3237
3238         gr_screen.gf_set_clear_color = gr_opengl_set_clear_color;
3239         
3240         Mouse_hidden++;
3241         gr_reset_clip();
3242         gr_clear();
3243         gr_flip();
3244         Mouse_hidden--;
3245 }