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