1 /*
2  * This file is part of the DXX-Rebirth project <https://www.dxx-rebirth.com/>.
3  * It is copyright by its individual contributors, as recorded in the
4  * project's Git history.  See COPYING.txt at the top level for license
5  * terms and a link to the Git history.
6  */
7 /*
8  *
9  * OGL video functions. - Added 9/15/99 Matthew Mueller
10  *
11  */
12 
13 #define DECLARE_VARS
14 
15 #ifdef RPI
16 // extra libraries for the Raspberry Pi
17 #include  <bcm_host.h>
18 #endif
19 
20 #include <stdlib.h>
21 #include <stdio.h>
22 #include <string.h>
23 #ifdef _MSC_VER
24 #include <windows.h>
25 #endif
26 
27 #if !defined(_MSC_VER) && !defined(macintosh)
28 #include <unistd.h>
29 #endif
30 #if !defined(macintosh)
31 #include <sys/types.h>
32 #include <sys/stat.h>
33 #include <fcntl.h>
34 #endif
35 
36 #include <algorithm>
37 #include <errno.h>
38 #include <SDL.h>
39 #include "game.h"
40 #include "gr.h"
41 #include "gamefont.h"
42 #include "palette.h"
43 #include "u_mem.h"
44 #include "dxxerror.h"
45 #include "inferno.h"
46 #include "strutil.h"
47 #include "args.h"
48 #include "physfsx.h"
49 #include "internal.h"
50 #include "console.h"
51 #include "config.h"
52 #include "vers_id.h"
53 
54 #if defined(__APPLE__) && defined(__MACH__)
55 #include <OpenGL/glu.h>
56 #else
57 #if DXX_USE_OGLES
58 #include <EGL/egl.h>
59 #include <X11/Xlib.h>
60 #include <X11/Xutil.h>
61 #include <SDL_syswm.h>
62 #endif
63 #endif
64 
65 #include "ogl_sync.h"
66 #include <memory>
67 
68 using std::min;
69 using std::max;
70 
71 namespace dcx {
72 
73 static int ogl_brightness_r, ogl_brightness_g, ogl_brightness_b;
74 
75 #if DXX_USE_OGLES
76 static int sdl_video_flags;
77 
78 #ifdef RPI
79 static EGL_DISPMANX_WINDOW_T nativewindow;
80 static DISPMANX_ELEMENT_HANDLE_T dispman_element=DISPMANX_NO_HANDLE;
81 static DISPMANX_DISPLAY_HANDLE_T dispman_display=DISPMANX_NO_HANDLE;
82 #endif
83 
84 #else
85 #if SDL_MAJOR_VERSION == 1
86 static int sdl_video_flags = SDL_OPENGL;
87 #elif SDL_MAJOR_VERSION == 2
88 SDL_Window *g_pRebirthSDLMainWindow;
89 static int g_iRebirthWindowX, g_iRebirthWindowY;
90 #endif
91 #endif
92 static ogl_sync sync_helper;
93 static int gr_installed;
94 static int gl_initialized;
95 int linedotscale=1; // scalar of glLinewidth and glPointSize - only calculated once when resolution changes
96 #ifdef RPI
97 static int sdl_no_modeswitch;
98 #else
99 enum { sdl_no_modeswitch = 0 };
100 #endif
101 
102 }
103 
104 namespace dsx {
105 
106 #if SDL_MAJOR_VERSION == 1
gr_set_mode_from_window_size()107 void gr_set_mode_from_window_size()
108 {
109 	gr_set_mode(Game_screen_mode);
110 }
111 #elif SDL_MAJOR_VERSION == 2
112 static void gr_set_mode_from_window_size(SDL_Window *const SDLWindow)
113 {
114 	assert(SDLWindow);
115 	int w, h;
116 	SDL_GL_GetDrawableSize(SDLWindow, &w, &h);
117 	gr_set_mode(screen_mode(w, h));
118 }
119 
120 void gr_set_mode_from_window_size()
121 {
122 	gr_set_mode_from_window_size(g_pRebirthSDLMainWindow);
123 }
124 #endif
125 
126 }
127 
128 #if DXX_USE_OGLES
129 static EGLDisplay eglDisplay=EGL_NO_DISPLAY;
130 static EGLConfig eglConfig;
131 static EGLSurface eglSurface=EGL_NO_SURFACE;
132 static EGLContext eglContext=EGL_NO_CONTEXT;
133 
TestEGLError(const char * pszLocation)134 static bool TestEGLError(const char* pszLocation)
135 {
136 	/*
137 	 * eglGetError returns the last error that has happened using egl,
138 	 * not the status of the last called function. The user has to
139 	 * check after every single egl call or at least once every frame.
140 	*/
141 	EGLint iErr = eglGetError();
142 	if (iErr != EGL_SUCCESS)
143 	{
144 		con_printf(CON_URGENT, "%s failed (%d).", pszLocation, iErr);
145 		return 0;
146 	}
147 
148 	return 1;
149 }
150 #endif
151 
152 namespace dcx {
153 
ogl_swap_buffers_internal(void)154 void ogl_swap_buffers_internal(void)
155 {
156 	sync_helper.before_swap();
157 #if DXX_USE_OGLES
158 	eglSwapBuffers(eglDisplay, eglSurface);
159 #else
160 #if SDL_MAJOR_VERSION == 1
161 	SDL_GL_SwapBuffers();
162 #elif SDL_MAJOR_VERSION == 2
163 	SDL_GL_SwapWindow(g_pRebirthSDLMainWindow);
164 #endif
165 #endif
166 	sync_helper.after_swap();
167 }
168 
169 }
170 
171 namespace dsx {
172 
173 #ifdef RPI
174 
175 // MH: I got the following constants for vc_dispmanx_element_change_attributes() from:
176 //     http://qt.gitorious.org/qt/qtbase/commit/5933205cfcd73481cb0645fa6183103063fe3e0d
177 //     I do not know where they got them from, but OTOH, they are quite obvious.
178 
179 // these constants are not in any headers (yet)
180 #define ELEMENT_CHANGE_LAYER          (1<<0)
181 #define ELEMENT_CHANGE_OPACITY        (1<<1)
182 #define ELEMENT_CHANGE_DEST_RECT      (1<<2)
183 #define ELEMENT_CHANGE_SRC_RECT       (1<<3)
184 #define ELEMENT_CHANGE_MASK_RESOURCE  (1<<4)
185 #define ELEMENT_CHANGE_TRANSFORM      (1<<5)
186 
rpi_destroy_element()187 static void rpi_destroy_element()
188 {
189 	if (dispman_element != DISPMANX_NO_HANDLE) {
190 		DISPMANX_UPDATE_HANDLE_T dispman_update;
191 		con_printf(CON_DEBUG, "RPi: destroying display manager element");
192 		dispman_update = vc_dispmanx_update_start( 0 );
193 		if (vc_dispmanx_element_remove( dispman_update, dispman_element)) {
194 			 con_printf(CON_URGENT, "RPi: failed to remove dispmanx element!");
195 		}
196 		vc_dispmanx_update_submit_sync( dispman_update );
197 		dispman_element = DISPMANX_NO_HANDLE;
198 	}
199 }
200 
rpi_setup_element(int x,int y,Uint32 video_flags,int update)201 static int rpi_setup_element(int x, int y, Uint32 video_flags, int update)
202 {
203 	// this code is based on the work of Ben O'Steen
204 	// http://benosteen.wordpress.com/2012/04/27/using-opengl-es-2-0-on-the-raspberry-pi-without-x-windows/
205 	// https://github.com/benosteen/opengles-book-samples/tree/master/Raspi
206 	DISPMANX_UPDATE_HANDLE_T dispman_update;
207 	VC_RECT_T dst_rect;
208 	VC_RECT_T src_rect;
209 	VC_DISPMANX_ALPHA_T alpha_descriptor;
210 
211 	uint32_t rpi_display_device=DISPMANX_ID_MAIN_LCD;
212 	uint32_t display_width;
213 	uint32_t display_height;
214 	int success;
215 
216 	success = graphics_get_display_size(rpi_display_device, &display_width, &display_height);
217 	if ( success < 0 ) {
218 		con_printf(CON_URGENT, "Could not get RPi display size, assuming 640x480");
219 		display_width=640;
220 		display_height=480;
221 	}
222 
223 	if (static_cast<uint32_t>(x) > display_width) {
224 		con_printf(CON_URGENT, "RPi: Requested width %d exceeds display width %u, scaling down!",
225 			x,display_width);
226 		x=static_cast<int>(display_width);
227 	}
228 	if (static_cast<uint32_t>(y) > display_height) {
229 		con_printf(CON_URGENT, "RPi: Requested height %d exceeds display height %u, scaling down!",
230 			y,display_height);
231 		y=static_cast<int>(display_height);
232 	}
233 
234 	con_printf(CON_DEBUG, "RPi: display resolution %ux%u, game resolution: %dx%d (%s)", display_width, display_height, x, y, (video_flags & SDL_FULLSCREEN)?"fullscreen":"windowed");
235 	if (video_flags & SDL_FULLSCREEN) {
236 		/* scale to the full display size... */
237 		dst_rect.x = 0;
238 		dst_rect.y = 0;
239 		dst_rect.width = display_width;
240 		dst_rect.height= display_height;
241 	} else {
242 		/* TODO: we could query the position of the X11 window here
243 		   and try to place the ovelray exactly above that...,
244 		   we would have to track window movements, though ... */
245 		dst_rect.x = 0;
246 		dst_rect.y = 0;
247 		dst_rect.width = static_cast<uint32_t>(x);
248 		dst_rect.height= static_cast<uint32_t>(y);
249 	}
250 
251 	src_rect.x = 0;
252 	src_rect.y = 0;
253 	src_rect.width = (static_cast<uint32_t>(x))<< 16;
254 	src_rect.height =(static_cast<uint32_t>(y))<< 16;
255 
256 	/* we do not want our overlay to be blended against the background */
257 	alpha_descriptor.flags=DISPMANX_FLAGS_ALPHA_FIXED_ALL_PIXELS;
258 	alpha_descriptor.opacity=0xffffffff;
259 	alpha_descriptor.mask=0;
260 
261 	// open display, if we do not already have one ...
262 	if (dispman_display == DISPMANX_NO_HANDLE) {
263 		con_printf(CON_DEBUG, "RPi: opening display: %u",rpi_display_device);
264 		dispman_display = vc_dispmanx_display_open(rpi_display_device);
265 		if (dispman_display == DISPMANX_NO_HANDLE) {
266 			con_printf(CON_URGENT,"RPi: failed to open display: %u",rpi_display_device);
267 		}
268 	}
269 
270 	if (dispman_element != DISPMANX_NO_HANDLE) {
271 		if (!update) {
272 			// if the element already exists, and we cannot update it, so recreate it
273 			rpi_destroy_element();
274 		}
275 	} else {
276 		// if the element does not exist, we cannot do an update
277 		update=0;
278 	}
279 
280 	dispman_update = vc_dispmanx_update_start( 0 );
281 
282 	if (update) {
283 		con_printf(CON_DEBUG, "RPi: updating display manager element");
284 		vc_dispmanx_element_change_attributes ( dispman_update, nativewindow.element,
285 							ELEMENT_CHANGE_DEST_RECT | ELEMENT_CHANGE_SRC_RECT,
286 							0 /*layer*/, 0 /*opacity*/,
287 							&dst_rect, &src_rect,
288 							0 /*mask*/,
289 							static_cast<DISPMANX_TRANSFORM_T>(VC_IMAGE_ROT0) /*transform*/);
290 	} else {
291 		// create a new element
292 		con_printf(CON_DEBUG, "RPi: creating display manager element");
293 		dispman_element = vc_dispmanx_element_add ( dispman_update, dispman_display,
294 								0 /*layer*/, &dst_rect, 0 /*src*/,
295 								&src_rect, DISPMANX_PROTECTION_NONE,
296 								&alpha_descriptor, NULL /*clamp*/,
297 								static_cast<DISPMANX_TRANSFORM_T>(VC_IMAGE_ROT0) /*transform*/);
298 		if (dispman_element == DISPMANX_NO_HANDLE) {
299 			con_printf(CON_URGENT,"RPi: failed to creat display manager elemenr");
300 		}
301 		nativewindow.element = dispman_element;
302 	}
303 	nativewindow.width = display_width;
304 	nativewindow.height = display_height;
305 	vc_dispmanx_update_submit_sync( dispman_update );
306 
307 	return 0;
308 }
309 
310 #endif // RPI
311 
312 #if DXX_USE_OGLES
ogles_destroy()313 static void ogles_destroy()
314 {
315 	if( eglDisplay != EGL_NO_DISPLAY ) {
316 		eglMakeCurrent(eglDisplay, NULL, NULL, EGL_NO_CONTEXT);
317 	}
318 
319 	if (eglContext != EGL_NO_CONTEXT) {
320 		con_printf(CON_DEBUG, "EGL: destroyig context");
321 		eglDestroyContext(eglDisplay, eglContext);
322 		eglContext = EGL_NO_CONTEXT;
323 	}
324 
325 	if (eglSurface != EGL_NO_SURFACE) {
326 		con_printf(CON_DEBUG, "EGL: destroyig surface");
327 		eglDestroySurface(eglDisplay, eglSurface);
328 		eglSurface = EGL_NO_SURFACE;
329 	}
330 
331 	if (eglDisplay != EGL_NO_DISPLAY) {
332 		con_printf(CON_DEBUG, "EGL: terminating");
333 		eglTerminate(eglDisplay);
334 		eglDisplay = EGL_NO_DISPLAY;
335 	}
336 }
337 #endif
338 
ogl_init_window(int w,int h)339 static int ogl_init_window(int w, int h)
340 {
341 #if DXX_USE_OGLES
342 	SDL_SysWMinfo info;
343 	Window    x11Window = 0;
344 	Display*  x11Display = 0;
345 	EGLint    ver_maj, ver_min;
346 	EGLint configAttribs[] =
347 	{
348 		EGL_RED_SIZE, 5,
349 		EGL_GREEN_SIZE, 6,
350 		EGL_BLUE_SIZE, 5,
351 		EGL_DEPTH_SIZE, 16,
352 		EGL_SURFACE_TYPE, EGL_WINDOW_BIT,
353 		EGL_RENDERABLE_TYPE, EGL_OPENGL_ES_BIT,
354 		EGL_NONE, EGL_NONE
355 	};
356 
357 	// explicitely request an OpenGL ES 1.x context
358         EGLint contextAttribs[] = { EGL_CONTEXT_CLIENT_VERSION, 1, EGL_NONE, EGL_NONE };
359 	// explicitely request a doublebuffering window
360         EGLint winAttribs[] = { EGL_RENDER_BUFFER, EGL_BACK_BUFFER, EGL_NONE, EGL_NONE };
361 
362 	int iConfigs;
363 #endif // OGLES
364 
365 #if SDL_MAJOR_VERSION == 1
366 	if (gl_initialized)
367 		ogl_smash_texture_list_internal();//if we are or were fullscreen, changing vid mode will invalidate current textures
368 
369 	SDL_WM_SetCaption(DESCENT_VERSION, DXX_SDL_WINDOW_CAPTION);
370 	if (const auto window_icon = SDL_LoadBMP(DXX_SDL_WINDOW_ICON_BITMAP))
371 		SDL_WM_SetIcon(window_icon, nullptr);
372 
373 	int use_x = w;
374 	int use_y = h;
375 	int use_bpp = CGameArg.DbgBpp;
376 	int use_flags = sdl_video_flags;
377 	if (sdl_no_modeswitch) {
378 		const SDL_VideoInfo *vinfo=SDL_GetVideoInfo();
379 		if (vinfo) {
380 			use_x=vinfo->current_w;
381 			use_y=vinfo->current_h;
382 			use_bpp=vinfo->vfmt->BitsPerPixel;
383 			use_flags=SDL_SWSURFACE | SDL_ANYFORMAT;
384 		} else {
385 			con_printf(CON_URGENT, "Could not query video info");
386 		}
387 	}
388 
389 	if (!SDL_SetVideoMode(use_x, use_y, use_bpp, use_flags))
390 	{
391 #ifdef RPI
392 		con_printf(CON_URGENT, "Could not set %dx%dx%d opengl video mode: %s\n (Ignored for RPI)",
393 			    w, h, CGameArg.DbgBpp, SDL_GetError());
394 #else
395 		Error("Could not set %dx%dx%d opengl video mode: %s\n", w, h, CGameArg.DbgBpp, SDL_GetError());
396 #endif
397 	}
398 #elif SDL_MAJOR_VERSION == 2
399 	const auto SDLWindow = g_pRebirthSDLMainWindow;
400 	if (!(SDL_GetWindowFlags(SDLWindow) & SDL_WINDOW_FULLSCREEN))
401 		SDL_SetWindowSize(SDLWindow, w, h);
402 #endif
403 
404 #if DXX_USE_OGLES
405 #ifndef RPI
406 	// NOTE: on the RPi, the EGL stuff is not connected to the X11 window,
407 	//       so there is no need to destroy and recreate this
408 	ogles_destroy();
409 #endif
410 
411 	SDL_VERSION(&info.version);
412 
413 	if (SDL_GetWMInfo(&info) > 0) {
414 		if (info.subsystem == SDL_SYSWM_X11) {
415 			x11Display = info.info.x11.display;
416 			x11Window = info.info.x11.window;
417 			con_printf (CON_DEBUG, "Display: %p, Window: %i ===", x11Display, static_cast<int>(x11Window));
418 		}
419 	}
420 
421 	if (eglDisplay == EGL_NO_DISPLAY) {
422 		const EGLNativeDisplayType desiredEGLDisplay =
423 #ifdef RPI
424 		EGL_DEFAULT_DISPLAY;
425 #else
426 		x11Display;
427 #endif
428 		eglDisplay = eglGetDisplay(desiredEGLDisplay);
429 		if (eglDisplay == EGL_NO_DISPLAY) {
430 			con_printf(CON_URGENT, "EGL: Error querying EGL Display");
431 		}
432 
433 		if (!eglInitialize(eglDisplay, &ver_maj, &ver_min)) {
434 			con_printf(CON_URGENT, "EGL: Error initializing EGL");
435 		} else {
436 			con_printf(CON_DEBUG, "EGL: Initialized, version: major %i minor %i", ver_maj, ver_min);
437 		}
438 	}
439 
440 
441 #ifdef RPI
442 	if (rpi_setup_element(w,h,sdl_video_flags,1)) {
443 		Error("RPi: Could not set up a %dx%d element\n", w, h);
444 	}
445 #endif
446 
447 	if (eglSurface == EGL_NO_SURFACE) {
448 		if (!eglChooseConfig(eglDisplay, configAttribs, &eglConfig, 1, &iConfigs) || (iConfigs != 1)) {
449 			con_printf(CON_URGENT, "EGL: Error choosing config");
450 		} else {
451 			con_printf(CON_DEBUG, "EGL: config chosen");
452 		}
453 
454 #ifdef RPI
455 		eglSurface = eglCreateWindowSurface(eglDisplay, eglConfig, static_cast<EGLNativeWindowType>(&nativewindow), winAttribs);
456 #else
457 		eglSurface = eglCreateWindowSurface(eglDisplay, eglConfig, x11Window, winAttribs);
458 #endif
459 		if ((!TestEGLError("eglCreateWindowSurface")) || eglSurface == EGL_NO_SURFACE) {
460 			con_printf(CON_URGENT, "EGL: Error creating window surface");
461 		} else {
462 			con_printf(CON_DEBUG, "EGL: Created window surface");
463 		}
464 	}
465 
466 	if (eglContext == EGL_NO_CONTEXT) {
467 		eglContext = eglCreateContext(eglDisplay, eglConfig, EGL_NO_CONTEXT, contextAttribs);
468 		if ((!TestEGLError("eglCreateContext")) || eglContext == EGL_NO_CONTEXT) {
469 			con_printf(CON_URGENT, "EGL: Error creating context");
470 		} else {
471 			con_printf(CON_DEBUG, "EGL: Created context");
472 		}
473 	}
474 
475 	eglMakeCurrent(eglDisplay, eglSurface, eglSurface, eglContext);
476 	if (!TestEGLError("eglMakeCurrent")) {
477 		con_printf(CON_URGENT, "EGL: Error making current");
478 	} else {
479 		con_printf(CON_DEBUG, "EGL: made context current");
480 	}
481 #endif
482 
483 	const auto w640 = w / 640;
484 	const auto h480 = h / 480;
485 	const auto min_wh = std::min(w640, h480);
486 	linedotscale = min_wh < 1 ? 1 : min_wh;
487 
488 	gl_initialized=1;
489 	return 0;
490 }
491 
492 }
493 
494 namespace dcx {
495 
gr_check_fullscreen(void)496 int gr_check_fullscreen(void)
497 {
498 #if SDL_MAJOR_VERSION == 1
499 	return !!(sdl_video_flags & SDL_FULLSCREEN);
500 #elif SDL_MAJOR_VERSION == 2
501 	return !!(SDL_GetWindowFlags(g_pRebirthSDLMainWindow) & SDL_WINDOW_FULLSCREEN);
502 #endif
503 }
504 
gr_toggle_fullscreen()505 void gr_toggle_fullscreen()
506 {
507 #if SDL_MAJOR_VERSION == 1
508 	const auto local_sdl_video_flags = (sdl_video_flags ^= SDL_FULLSCREEN);
509 	if (gl_initialized)
510 	{
511 		if (sdl_no_modeswitch == 0) {
512 			auto gsm = Game_screen_mode;
513 			const auto DbgBpp = CGameArg.DbgBpp;
514 			if (!SDL_VideoModeOK(gsm.width, gsm.height, DbgBpp, local_sdl_video_flags))
515 			{
516 				con_printf(CON_URGENT, "Cannot set %ix%i. Fallback to 640x480", gsm.width, gsm.height);
517 				gsm.width = 640;
518 				gsm.height = 480;
519 				Game_screen_mode = gsm;
520 			}
521 			if (!SDL_SetVideoMode(gsm.width, gsm.height, DbgBpp, local_sdl_video_flags))
522 			{
523 				Error("Could not set %dx%dx%d opengl video mode: %s\n", gsm.width, gsm.height, DbgBpp, SDL_GetError());
524 			}
525 		}
526 #ifdef RPI
527 		if (rpi_setup_element(SM_W(Game_screen_mode), SM_H(Game_screen_mode), local_sdl_video_flags, 1)) {
528 			 Error("RPi: Could not set up %dx%d element\n", SM_W(Game_screen_mode), SM_H(Game_screen_mode));
529 		}
530 #endif
531 	}
532 
533 	gr_remap_color_fonts();
534 
535 	if (gl_initialized) // update viewing values for menus
536 	{
537 		glMatrixMode(GL_PROJECTION);
538 		glLoadIdentity();
539 #if DXX_USE_OGLES
540 		glOrthof(0.0, 1.0, 0.0, 1.0, -1.0, 1.0);
541 #else
542  		glOrtho(0.0, 1.0, 0.0, 1.0, -1.0, 1.0);
543 #endif
544 		glMatrixMode(GL_MODELVIEW);
545 		glLoadIdentity();//clear matrix
546 		glEnable(GL_BLEND);
547 		glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
548 		ogl_smash_texture_list_internal();//if we are or were fullscreen, changing vid mode will invalidate current textures
549 	}
550 	CGameCfg.WindowMode = !(local_sdl_video_flags & SDL_FULLSCREEN);
551 #elif SDL_MAJOR_VERSION == 2
552 	const auto SDLWindow = g_pRebirthSDLMainWindow;
553 	const auto is_fullscreen_before_change = SDL_GetWindowFlags(SDLWindow) & SDL_WINDOW_FULLSCREEN;
554 	CGameCfg.WindowMode = !!is_fullscreen_before_change;
555 	if (!is_fullscreen_before_change)
556 		SDL_GetWindowPosition(SDLWindow, &g_iRebirthWindowX, &g_iRebirthWindowY);
557 	SDL_SetWindowFullscreen(SDLWindow, is_fullscreen_before_change ? 0 : SDL_WINDOW_FULLSCREEN_DESKTOP);
558 	if (is_fullscreen_before_change)
559 	{
560 		const auto mode = Game_screen_mode;
561 		SDL_SetWindowPosition(SDLWindow, g_iRebirthWindowX, g_iRebirthWindowY);
562 		SDL_SetWindowSize(SDLWindow, SM_W(mode), SM_H(mode));
563 	}
564 	gr_set_mode_from_window_size(SDLWindow);
565 #endif
566 }
567 
ogl_init_state(void)568 static void ogl_init_state(void)
569 {
570 	/* select clearing (background) color   */
571 	glClearColor(0.0, 0.0, 0.0, 0.0);
572 
573 	/* initialize viewing values */
574 	glMatrixMode(GL_PROJECTION);
575 	glLoadIdentity();
576 #if DXX_USE_OGLES
577 	glOrthof(0.0, 1.0, 0.0, 1.0, -1.0, 1.0);
578 #else
579  	glOrtho(0.0, 1.0, 0.0, 1.0, -1.0, 1.0);
580 #endif
581 	glMatrixMode(GL_MODELVIEW);
582 	glLoadIdentity();//clear matrix
583 	glEnable(GL_BLEND);
584 	glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
585 	gr_palette_step_up(0,0,0);//in case its left over from in game
586 
587 	ogl_init_pixel_buffers(grd_curscreen->get_screen_width(), grd_curscreen->get_screen_height());
588 }
589 
590 }
591 
592 namespace dsx {
593 
ogl_tune_for_current(void)594 static void ogl_tune_for_current(void)
595 {
596 	const auto gl_vendor = reinterpret_cast<const char *>(glGetString(GL_VENDOR));
597 	const auto gl_renderer = reinterpret_cast<const char *>(glGetString(GL_RENDERER));
598 	const auto gl_version = reinterpret_cast<const char *>(glGetString(GL_VERSION));
599 
600 	con_printf(CON_VERBOSE, "DXX-Rebirth: OpenGL: vendor: %s", gl_vendor);
601 	con_printf(CON_VERBOSE, "DXX-Rebirth: OpenGL: renderer: %s", gl_renderer);
602 
603 	if (gl_renderer)
604 	{
605 	//add driver specific hacks here.  whee.
606 	if ((d_stricmp(gl_renderer,"Mesa NVIDIA RIVA 1.0\n")==0 || d_stricmp(gl_renderer,"Mesa NVIDIA RIVA 1.2\n")==0) && d_stricmp(gl_version,"1.2 Mesa 3.0")==0)
607 	{
608 		con_puts(CON_VERBOSE, "DXX-Rebirth: OpenGL renderer is blacklisted for GL intensity, GL read pixel, and GL GetTexLevel");
609 		CGameArg.DbgGlIntensity4Ok = false;	//ignores alpha, always black background instead of transparent.
610 		CGameArg.DbgGlReadPixelsOk = false;	//either just returns all black, or kills the X server entirely
611 		CGameArg.DbgGlGetTexLevelParamOk = false;	//returns random data..
612 	}
613 	if (d_stricmp(gl_vendor,"Matrox Graphics Inc.")==0)
614 	{
615 		con_puts(CON_VERBOSE, "DXX-Rebirth: OpenGL renderer is blacklisted for GL intensity");
616 		//displays garbage. reported by
617 		//  redomen@crcwnet.com (render="Matrox G400" version="1.1.3 5.52.015")
618 		//  orulz (Matrox G200)
619 		CGameArg.DbgGlIntensity4Ok = 0;
620 	}
621 #ifdef macintosh
622 	if (d_stricmp(gl_renderer,"3dfx Voodoo 3")==0) // strangely, includes Voodoo 2
623 		CGameArg.DbgGlGetTexLevelParamOk = false;	// Always returns 0
624 #endif
625 	}
626 
627 #ifndef NDEBUG
628 	con_printf(CON_VERBOSE, "DXX-Rebirth: OpenGL: gl_intensity4:%i gl_luminance4_alpha4:%i gl_rgba2:%i gl_readpixels:%i gl_gettexlevelparam:%i", CGameArg.DbgGlIntensity4Ok, CGameArg.DbgGlLuminance4Alpha4Ok, CGameArg.DbgGlRGBA2Ok, CGameArg.DbgGlReadPixelsOk, CGameArg.DbgGlGetTexLevelParamOk);
629 #endif
630 	if (ogl_maxanisotropy < 1.0f && CGameCfg.TexAnisotropy)
631 	{
632 		con_puts(CON_VERBOSE, "DXX-Rebirth: OpenGL: anisotropic texture filter not supported");
633 		CGameCfg.TexAnisotropy = false;
634 	}
635 }
636 
637 }
638 
639 namespace dcx {
640 
641 #if SDL_MAJOR_VERSION == 1
642 // returns possible (fullscreen) resolutions if any.
gr_list_modes(std::array<screen_mode,50> & gsmodes)643 uint_fast32_t gr_list_modes(std::array<screen_mode, 50> &gsmodes)
644 {
645 	SDL_Rect** modes;
646 	int modesnum = 0;
647 #if DXX_USE_OGLES
648 	int sdl_check_flags = SDL_FULLSCREEN; // always use Fullscreen as lead.
649 #else
650 	int sdl_check_flags = SDL_OPENGL | SDL_FULLSCREEN; // always use Fullscreen as lead.
651 #endif
652 
653 	if (sdl_no_modeswitch) {
654 		/* TODO: we could use the tvservice to list resolutions on the RPi */
655 		return 0;
656 	}
657 
658 	modes = SDL_ListModes(NULL, sdl_check_flags);
659 
660 	if (modes == reinterpret_cast<SDL_Rect **>(0)) // check if we get any modes - if not, return 0
661 		return 0;
662 
663 
664 	if (modes == reinterpret_cast<SDL_Rect**>(-1))
665 	{
666 		return 0; // can obviously use any resolution... strange!
667 	}
668 	else
669 	{
670 		for (int i = 0; modes[i]; ++i)
671 		{
672 			if (modes[i]->w > 0xFFF0 || modes[i]->h > 0xFFF0 // resolutions saved in 32bits. so skip bigger ones (unrealistic in 2010) (changed to 0xFFF0 to fix warning)
673 				|| modes[i]->w < 320 || modes[i]->h < 200) // also skip everything smaller than 320x200
674 				continue;
675 			gsmodes[modesnum].width = modes[i]->w;
676 			gsmodes[modesnum].height = modes[i]->h;
677 			modesnum++;
678 			if (modesnum >= gsmodes.size()) // that really seems to be enough big boy.
679 				break;
680 		}
681 		return modesnum;
682 	}
683 }
684 #endif
685 
686 }
687 
688 namespace dsx {
689 
690 #if SDL_MAJOR_VERSION == 1
gr_check_mode(const screen_mode mode)691 static int gr_check_mode(const screen_mode mode)
692 {
693 	if (sdl_no_modeswitch == 0) {
694 		return SDL_VideoModeOK(SM_W(mode), SM_H(mode), CGameArg.DbgBpp, sdl_video_flags);
695 	} else {
696 		// just tell the caller that any mode is valid...
697 		return 32;
698 	}
699 }
700 #endif
701 
gr_set_mode(screen_mode mode)702 int gr_set_mode(screen_mode mode)
703 {
704 	unsigned char *gr_bm_data;
705 #if SDL_MAJOR_VERSION == 1
706 	if (!gr_check_mode(mode))
707 	{
708 		con_printf(CON_URGENT, "Cannot set %ix%i. Fallback to 640x480", mode.width, mode.height);
709 		mode.width = 640;
710 		mode.height = 480;
711 		Game_screen_mode = mode;
712 	}
713 #endif
714 	const uint_fast32_t w = SM_W(mode), h = SM_H(mode);
715 
716 	gr_bm_data = grd_curscreen->sc_canvas.cv_bitmap.get_bitmap_data();//since we use realloc, we want to keep this pointer around.
717 	auto gr_new_bm_data = reinterpret_cast<uint8_t *>(d_realloc(gr_bm_data, w * h));
718 	if (!gr_new_bm_data)
719 		return 0;
720 	*grd_curscreen = {};
721 	grd_curscreen->set_screen_width_height(w, h);
722 	grd_curscreen->sc_aspect = fixdiv(grd_curscreen->get_screen_width() * GameCfg.AspectX, grd_curscreen->get_screen_height() * GameCfg.AspectY);
723 	gr_init_canvas(grd_curscreen->sc_canvas, gr_new_bm_data, bm_mode::ogl, w, h);
724 
725 	ogl_init_window(w,h);//platform specific code
726 	ogl_extensions_init();
727 	ogl_tune_for_current();
728 	sync_helper.init(CGameArg.OglSyncMethod, CGameArg.OglSyncWait);
729 
730 	OGL_VIEWPORT(0,0,w,h);
731 	ogl_init_state();
732 	gamefont_choose_game_font(w,h);
733 	gr_remap_color_fonts();
734 
735 	return 0;
736 }
737 
738 #define GLstrcmptestr(a,b) if (d_stricmp(a,#b)==0 || d_stricmp(a,"GL_" #b)==0)return GL_ ## b;
739 
740 #ifdef _WIN32
741 constexpr char OglLibPath[]="opengl32.dll";
742 
743 static int ogl_rt_loaded=0;
ogl_init_load_library(void)744 static int ogl_init_load_library(void)
745 {
746 	int retcode=0;
747 	if (!ogl_rt_loaded)
748 	{
749 		retcode = OpenGL_LoadLibrary(true, OglLibPath);
750 		if(retcode)
751 		{
752 			if(!glEnd)
753 			{
754 				Error("Opengl: Functions not imported\n");
755 			}
756 		}
757 		else
758 		{
759 			Error("Opengl: error loading %s\n", OglLibPath);
760 		}
761 		ogl_rt_loaded=1;
762 	}
763 	return retcode;
764 }
765 #endif
766 
gr_set_attributes(void)767 void gr_set_attributes(void)
768 {
769 #if !DXX_USE_OGLES
770 	SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 16);
771 	SDL_GL_SetAttribute(SDL_GL_STENCIL_SIZE,0);
772 	SDL_GL_SetAttribute(SDL_GL_ACCUM_RED_SIZE,0);
773 	SDL_GL_SetAttribute(SDL_GL_ACCUM_GREEN_SIZE,0);
774 	SDL_GL_SetAttribute(SDL_GL_ACCUM_BLUE_SIZE,0);
775 	SDL_GL_SetAttribute(SDL_GL_ACCUM_ALPHA_SIZE,0);
776 	SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER,1);
777 #if SDL_MAJOR_VERSION == 1
778 	SDL_GL_SetAttribute(SDL_GL_SWAP_CONTROL, CGameCfg.VSync);
779 #elif SDL_MAJOR_VERSION == 2
780 	SDL_GL_SetSwapInterval(CGameCfg.VSync ? 1 : 0);
781 #endif
782 	int buffers, samples;
783 	if (CGameCfg.Multisample)
784 	{
785 		buffers = 1;
786 		samples = 4;
787 	}
788 	else
789 	{
790 		buffers = samples = 0;
791 	}
792 	SDL_GL_SetAttribute(SDL_GL_MULTISAMPLEBUFFERS, buffers);
793 	SDL_GL_SetAttribute(SDL_GL_MULTISAMPLESAMPLES, samples);
794 #endif
795 	ogl_smash_texture_list_internal();
796 	gr_remap_color_fonts();
797 }
798 
gr_init()799 int gr_init()
800 {
801 	// Only do this function once!
802 	if (gr_installed==1)
803 		return -1;
804 
805 #ifdef RPI
806 	// Initialize the broadcom host library
807 	// we have to call this before we can create an OpenGL ES context
808 	bcm_host_init();
809 
810 	// Check if we are running with SDL directfb driver ...
811 	char sdl_driver[32];
812 	if (auto sdl_driver_ret = SDL_VideoDriverName(sdl_driver, sizeof(sdl_driver)))
813 	{
814 		if (strcmp(sdl_driver_ret,"x11")) {
815 			con_printf(CON_URGENT,"RPi: activating hack for console driver");
816 			sdl_no_modeswitch=1;
817 		}
818 	}
819 #endif
820 
821 #ifdef _WIN32
822 	ogl_init_load_library();
823 #endif
824 
825 #if SDL_MAJOR_VERSION == 1
826 	if (!CGameCfg.WindowMode && !CGameArg.SysWindow)
827 		sdl_video_flags|=SDL_FULLSCREEN;
828 
829 	if (CGameArg.SysNoBorders)
830 		sdl_video_flags|=SDL_NOFRAME;
831 #elif SDL_MAJOR_VERSION == 2
832 	assert(!g_pRebirthSDLMainWindow);
833 	unsigned sdl_window_flags = SDL_WINDOW_OPENGL;
834 	if (CGameArg.SysNoBorders)
835 		sdl_window_flags |= SDL_WINDOW_BORDERLESS;
836 	if (!CGameCfg.WindowMode && !CGameArg.SysWindow)
837 		sdl_window_flags |= SDL_WINDOW_FULLSCREEN_DESKTOP;
838 	const auto mode = Game_screen_mode;
839 	const auto SDLWindow = SDL_CreateWindow(DESCENT_VERSION, SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, SM_W(mode), SM_H(mode), sdl_window_flags);
840 	if (!SDLWindow)
841 		return -1;
842 	SDL_GetWindowPosition(SDLWindow, &g_iRebirthWindowX, &g_iRebirthWindowY);
843 	g_pRebirthSDLMainWindow = SDLWindow;
844 	SDL_GL_CreateContext(SDLWindow);
845 	if (const auto window_icon = SDL_LoadBMP(DXX_SDL_WINDOW_ICON_BITMAP))
846 		SDL_SetWindowIcon(SDLWindow, window_icon);
847 #endif
848 
849 	gr_set_attributes();
850 
851 	ogl_init_texture_list_internal();
852 
853 	grd_curscreen = std::make_unique<grs_screen>();
854 	*grd_curscreen = {};
855 	grd_curscreen->sc_canvas.cv_bitmap.bm_data = NULL;
856 
857 	// Set the mode.
858 	grd_curscreen->sc_canvas.cv_fade_level = GR_FADE_OFF;
859 	grd_curscreen->sc_canvas.cv_font = NULL;
860 	grd_curscreen->sc_canvas.cv_font_fg_color = 0;
861 	grd_curscreen->sc_canvas.cv_font_bg_color = 0;
862 	gr_set_current_canvas(grd_curscreen->sc_canvas);
863 
864 	ogl_init_pixel_buffers(256, 128);       // for gamefont_init
865 
866 	gr_installed = 1;
867 
868 	return 0;
869 }
870 
gr_close()871 void gr_close()
872 {
873 	ogl_brightness_r = ogl_brightness_g = ogl_brightness_b = 0;
874 
875 	if (gl_initialized)
876 	{
877 		ogl_smash_texture_list_internal();
878 		sync_helper.deinit();
879 	}
880 
881 	if (grd_curscreen)
882 	{
883 		if (grd_curscreen->sc_canvas.cv_bitmap.bm_mdata)
884 			d_free(grd_curscreen->sc_canvas.cv_bitmap.bm_mdata);
885 		/* Resetting grd_curscreen frees the default canvas, so set
886 		 * grd_curcanv to nullptr since no canvas is available after
887 		 * this block ends.
888 		 */
889 		grd_curcanv = nullptr;
890 		grd_curscreen.reset();
891 	}
892 	ogl_close_pixel_buffers();
893 #ifdef _WIN32
894 	if (ogl_rt_loaded)
895 		OpenGL_LoadLibrary(false, OglLibPath);
896 #endif
897 
898 #if DXX_USE_OGLES
899 	ogles_destroy();
900 #ifdef RPI
901 	con_printf(CON_DEBUG, "RPi: cleanuing up");
902 	if (dispman_display != DISPMANX_NO_HANDLE) {
903 		rpi_destroy_element();
904 		con_printf(CON_DEBUG, "RPi: closing display");
905 		vc_dispmanx_display_close(dispman_display);
906 		dispman_display = DISPMANX_NO_HANDLE;
907 	}
908 #endif
909 #endif
910 }
911 
912 }
913 
914 namespace dcx {
915 
ogl_upixelc(const grs_bitmap & cv_bitmap,unsigned x,unsigned y,const color_palette_index c)916 void ogl_upixelc(const grs_bitmap &cv_bitmap, unsigned x, unsigned y, const color_palette_index c)
917 {
918 	std::array<GLfloat, 2> vertices = {{
919 		(x + cv_bitmap.bm_x) / static_cast<float>(last_width),
920 		static_cast<GLfloat>(1.0 - (y + cv_bitmap.bm_y) / static_cast<float>(last_height))
921 	}};
922 	const auto cr = static_cast<GLfloat>(CPAL2Tr(c));
923 	const auto cg = static_cast<GLfloat>(CPAL2Tg(c));
924 	const auto cb = static_cast<GLfloat>(CPAL2Tb(c));
925 	GLfloat color_array[] = {
926 		cr, cg, cb, 1.0,
927 		cr, cg, cb, 1.0,
928 		cr, cg, cb, 1.0,
929 		cr, cg, cb, 1.0
930 	};
931 
932 	OGL_DISABLE(TEXTURE_2D);
933 	glPointSize(linedotscale);
934 	glEnableClientState(GL_VERTEX_ARRAY);
935 	glEnableClientState(GL_COLOR_ARRAY);
936 	glVertexPointer(2, GL_FLOAT, 0, vertices.data());
937 	glColorPointer(4, GL_FLOAT, 0, color_array);
938 	glDrawArrays(GL_POINTS, 0, 1);
939 	glDisableClientState(GL_VERTEX_ARRAY);
940 	glDisableClientState(GL_COLOR_ARRAY);
941 }
942 
ogl_ugpixel(const grs_bitmap & bitmap,unsigned x,unsigned y)943 color_palette_index ogl_ugpixel(const grs_bitmap &bitmap, unsigned x, unsigned y)
944 {
945 	ubyte buf[4];
946 
947 #if !DXX_USE_OGLES
948 	GLint gl_draw_buffer;
949 	glGetIntegerv(GL_DRAW_BUFFER, &gl_draw_buffer);
950 	glReadBuffer(gl_draw_buffer);
951 #endif
952 
953 	glReadPixels(bitmap.bm_x + x, SHEIGHT - bitmap.bm_y - y, 1, 1, GL_RGBA, GL_UNSIGNED_BYTE, buf);
954 
955 	return gr_find_closest_color(buf[0]/4, buf[1]/4, buf[2]/4);
956 }
957 
ogl_urect(grs_canvas & canvas,const int left,const int top,const int right,const int bot,const color_palette_index c)958 void ogl_urect(grs_canvas &canvas, const int left, const int top, const int right, const int bot, const color_palette_index c)
959 {
960 	GLfloat xo, yo, xf, yf, color_r, color_g, color_b, color_a;
961 
962 	glEnableClientState(GL_VERTEX_ARRAY);
963 	glEnableClientState(GL_COLOR_ARRAY);
964 
965 	xo = (left + canvas.cv_bitmap.bm_x) / static_cast<float>(last_width);
966 	xf = (right + 1 + canvas.cv_bitmap.bm_x) / static_cast<float>(last_width);
967 	yo = 1.0 - (top + canvas.cv_bitmap.bm_y) / static_cast<float>(last_height);
968 	yf = 1.0 - (bot + 1 + canvas.cv_bitmap.bm_y) / static_cast<float>(last_height);
969 
970 	OGL_DISABLE(TEXTURE_2D);
971 
972 	color_r = CPAL2Tr(c);
973 	color_g = CPAL2Tg(c);
974 	color_b = CPAL2Tb(c);
975 
976 	if (canvas.cv_fade_level >= GR_FADE_OFF)
977 		color_a = 1.0;
978 	else
979 		color_a = 1.0 - static_cast<float>(canvas.cv_fade_level) / (static_cast<float>(GR_FADE_LEVELS) - 1.0);
980 
981 	std::array<GLfloat, 16> color_array;
982 	color_array[0] = color_array[4] = color_array[8] = color_array[12] = color_r;
983 	color_array[1] = color_array[5] = color_array[9] = color_array[13] = color_g;
984 	color_array[2] = color_array[6] = color_array[10] = color_array[14] = color_b;
985 	color_array[3] = color_array[7] = color_array[11] = color_array[15] = color_a;
986 
987 	std::array<GLfloat, 8> vertices;
988 	vertices[0] = xo;
989 	vertices[1] = yo;
990 	vertices[2] = xo;
991 	vertices[3] = yf;
992 	vertices[4] = xf;
993 	vertices[5] = yf;
994 	vertices[6] = xf;
995 	vertices[7] = yo;
996 	glVertexPointer(2, GL_FLOAT, 0, vertices.data());
997 	glColorPointer(4, GL_FLOAT, 0, color_array.data());
998 	glDrawArrays(GL_TRIANGLE_FAN, 0, 4);//replaced GL_QUADS
999 	glDisableClientState(GL_VERTEX_ARRAY);
1000 	glDisableClientState(GL_COLOR_ARRAY);
1001 }
1002 
ogl_ulinec(grs_canvas & canvas,const int left,const int top,const int right,const int bot,const int c)1003 void ogl_ulinec(grs_canvas &canvas, const int left, const int top, const int right, const int bot, const int c)
1004 {
1005 	GLfloat xo,yo,xf,yf;
1006 	GLfloat fade_alpha = (canvas.cv_fade_level >= GR_FADE_OFF)
1007 		? 1.0
1008 		: 1.0 - static_cast<float>(canvas.cv_fade_level) / (static_cast<float>(GR_FADE_LEVELS) - 1.0);
1009 	GLfloat color_array[] = {
1010 		static_cast<GLfloat>(CPAL2Tr(c)), static_cast<GLfloat>(CPAL2Tg(c)), static_cast<GLfloat>(CPAL2Tb(c)), fade_alpha,
1011 		static_cast<GLfloat>(CPAL2Tr(c)), static_cast<GLfloat>(CPAL2Tg(c)), static_cast<GLfloat>(CPAL2Tb(c)), fade_alpha,
1012 		static_cast<GLfloat>(CPAL2Tr(c)), static_cast<GLfloat>(CPAL2Tg(c)), static_cast<GLfloat>(CPAL2Tb(c)), 1.0,
1013 		static_cast<GLfloat>(CPAL2Tr(c)), static_cast<GLfloat>(CPAL2Tg(c)), static_cast<GLfloat>(CPAL2Tb(c)), fade_alpha
1014 	};
1015 
1016 	glEnableClientState(GL_VERTEX_ARRAY);
1017 	glEnableClientState(GL_COLOR_ARRAY);
1018 
1019 	xo = (left + canvas.cv_bitmap.bm_x) / static_cast<float>(last_width);
1020 	xf = (right + canvas.cv_bitmap.bm_x) / static_cast<float>(last_width);
1021 	yo = 1.0 - (top + canvas.cv_bitmap.bm_y + 0.5) / static_cast<float>(last_height);
1022 	yf = 1.0 - (bot + canvas.cv_bitmap.bm_y + 0.5) / static_cast<float>(last_height);
1023 
1024 	OGL_DISABLE(TEXTURE_2D);
1025 
1026 	std::array<GLfloat, 4> vertices = {{
1027 		xo,
1028 		yo,
1029 		xf,
1030 		yf,
1031 	}};
1032 
1033 	glVertexPointer(2, GL_FLOAT, 0, vertices.data());
1034 	glColorPointer(4, GL_FLOAT, 0, color_array);
1035 	glDrawArrays(GL_LINES, 0, 2);
1036 	glDisableClientState(GL_VERTEX_ARRAY);
1037 	glDisableClientState(GL_COLOR_ARRAY);
1038 }
1039 
1040 static GLfloat last_r, last_g, last_b;
1041 static int do_pal_step;
1042 
ogl_do_palfx(void)1043 void ogl_do_palfx(void)
1044 {
1045 	OGL_DISABLE(TEXTURE_2D);
1046 
1047 	glEnableClientState(GL_VERTEX_ARRAY);
1048 	glEnableClientState(GL_COLOR_ARRAY);
1049 
1050 	GLfloat alast_r = last_r;
1051 	GLfloat alast_g = last_g;
1052 	GLfloat alast_b = last_b;
1053 
1054 	if (!do_pal_step) {
1055 		return;
1056 	}
1057 	else if (last_r <= 0 && last_g <= 0 && last_b <= 0)
1058 	{
1059 		// scale negative effect by 2.5 to match D1/D2 on GL
1060 		// also make values positive to actually have an effect
1061 		alast_r = last_r * -2.5;
1062 		alast_g = last_g * -2.5;
1063 		alast_b = last_b * -2.5;
1064 
1065 		glEnable(GL_BLEND);
1066 		glBlendFunc(GL_ZERO,GL_ONE_MINUS_SRC_COLOR);
1067 	}
1068 	else
1069 	{
1070 		glEnable(GL_BLEND);
1071 		glBlendFunc(GL_ONE,GL_ONE);
1072 	}
1073 
1074 	GLfloat color_array[] = {
1075 		alast_r, alast_g, alast_b, 1.0,
1076 		alast_r, alast_g, alast_b, 1.0,
1077 		alast_r, alast_g, alast_b, 1.0,
1078 		alast_r, alast_g, alast_b, 1.0
1079 	};
1080 
1081 	std::array<GLfloat, 8> vertices = {{
1082 		0, 0, 0, 1, 1, 1, 1, 0
1083 	}};
1084 	glVertexPointer(2, GL_FLOAT, 0, vertices.data());
1085 	glColorPointer(4, GL_FLOAT, 0, color_array);
1086 	glDrawArrays(GL_TRIANGLE_FAN, 0, 4);//replaced GL_QUADS
1087 	glDisableClientState(GL_VERTEX_ARRAY);
1088 	glDisableClientState(GL_COLOR_ARRAY);
1089 	glEnable(GL_BLEND);
1090 	glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
1091 }
1092 
1093 static int ogl_brightness_ok;
1094 static int old_b_r, old_b_g, old_b_b;
1095 
gr_apply_gamma_clamp(int v)1096 inline int gr_apply_gamma_clamp(int v)
1097 {
1098 	if (v >= 0)
1099 		return max(v + gr_palette_gamma, 0);
1100 	else
1101 		return min(v + gr_palette_gamma, 0);
1102 }
1103 
gr_palette_step_up(int r,int g,int b)1104 void gr_palette_step_up(int r, int g, int b)
1105 {
1106 	old_b_r = ogl_brightness_r;
1107 	old_b_g = ogl_brightness_g;
1108 	old_b_b = ogl_brightness_b;
1109 
1110 	ogl_brightness_r = gr_apply_gamma_clamp(r);
1111 	ogl_brightness_g = gr_apply_gamma_clamp(g);
1112 	ogl_brightness_b = gr_apply_gamma_clamp(b);
1113 
1114 	if (!ogl_brightness_ok)
1115 	{
1116 		last_r = ogl_brightness_r / 63.0;
1117 		last_g = ogl_brightness_g / 63.0;
1118 		last_b = ogl_brightness_b / 63.0;
1119 
1120 		do_pal_step = (r || g || b || gr_palette_gamma);
1121 	}
1122 	else
1123 	{
1124 		do_pal_step = 0;
1125 	}
1126 }
1127 
gr_palette_load(palette_array_t & pal)1128 void gr_palette_load( palette_array_t &pal )
1129 {
1130 	copy_bound_palette(gr_current_pal, pal);
1131 
1132 	gr_palette_step_up(0, 0, 0); // make ogl_setbrightness_internal get run so that menus get brightened too.
1133 	reset_computed_colors();
1134 }
1135 
1136 #define GL_BGR_EXT 0x80E0
1137 
1138 struct TGA_header
1139 {
1140       unsigned char TGAheader[12];
1141       unsigned char header[6];
1142 };
1143 
1144 //writes out an uncompressed RGB .tga file
1145 //if we got really spiffy, we could optionally link in libpng or something, and use that.
1146 #if DXX_USE_SCREENSHOT_FORMAT_LEGACY
write_bmp(PHYSFS_File * const TGAFile,const unsigned w,const unsigned h)1147 void write_bmp(PHYSFS_File *const TGAFile, const unsigned w, const unsigned h)
1148 {
1149 	TGA_header TGA;
1150 	GLbyte HeightH,HeightL,WidthH,WidthL;
1151 	RAIIdmem<uint8_t[]> buf;
1152 	const unsigned buffer_size_TGA = w * h * 3;
1153 	CALLOC(buf, uint8_t[], buffer_size_TGA);
1154 
1155 	RAIIdmem<uint8_t[]> rgbaBuf;
1156 	CALLOC(rgbaBuf, uint8_t[], w * h * 4);
1157 	glReadPixels(0, 0, w, h, GL_RGBA, GL_UNSIGNED_BYTE, rgbaBuf.get());
1158 	for(unsigned int pixel = 0; pixel < w * h; pixel++) {
1159 		buf[pixel * 3] = rgbaBuf[pixel * 4 + 2];
1160 		buf[pixel * 3 + 1] = rgbaBuf[pixel * 4 + 1];
1161 		buf[pixel * 3 + 2] = rgbaBuf[pixel * 4];
1162 	}
1163 
1164 	HeightH = static_cast<GLbyte>(h / 256);
1165 	HeightL = static_cast<GLbyte>(h % 256);
1166 	WidthH  = static_cast<GLbyte>(w / 256);
1167 	WidthL  = static_cast<GLbyte>(w % 256);
1168 	// Write TGA Header
1169 	TGA.TGAheader[0] = 0;
1170 	TGA.TGAheader[1] = 0;
1171 	TGA.TGAheader[2] = 2;
1172 	TGA.TGAheader[3] = 0;
1173 	TGA.TGAheader[4] = 0;
1174 	TGA.TGAheader[5] = 0;
1175 	TGA.TGAheader[6] = 0;
1176 	TGA.TGAheader[7] = 0;
1177 	TGA.TGAheader[8] = 0;
1178 	TGA.TGAheader[9] = 0;
1179 	TGA.TGAheader[10] = 0;
1180 	TGA.TGAheader[11] = 0;
1181 	TGA.header[0] = WidthL;
1182 	TGA.header[1] = WidthH;
1183 	TGA.header[2] = HeightL;
1184 	TGA.header[3] = HeightH;
1185 	TGA.header[4] = static_cast<GLbyte>(24);
1186 	TGA.header[5] = 0;
1187 	PHYSFS_write(TGAFile,&TGA,sizeof(TGA_header),1);
1188 	PHYSFS_write(TGAFile,buf, buffer_size_TGA * sizeof(unsigned char),1);
1189 }
1190 #endif
1191 
1192 }
1193