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