src/video/SDL_video.c
author Sam Lantinga <slouken@lokigames.com>
Tue, 01 May 2001 21:12:57 +0000
changeset 14 c3e9d4a623c1
parent 11 7b94b6379341
child 19 8cc4dbfab9ab
permissions -rw-r--r--
Fixed stuck keys when changing the video mode
     1 /*
     2     SDL - Simple DirectMedia Layer
     3     Copyright (C) 1997, 1998, 1999, 2000, 2001  Sam Lantinga
     4 
     5     This library is free software; you can redistribute it and/or
     6     modify it under the terms of the GNU Library General Public
     7     License as published by the Free Software Foundation; either
     8     version 2 of the License, or (at your option) any later version.
     9 
    10     This library is distributed in the hope that it will be useful,
    11     but WITHOUT ANY WARRANTY; without even the implied warranty of
    12     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
    13     Library General Public License for more details.
    14 
    15     You should have received a copy of the GNU Library General Public
    16     License along with this library; if not, write to the Free
    17     Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
    18 
    19     Sam Lantinga
    20     slouken@devolution.com
    21 */
    22 
    23 #ifdef SAVE_RCSID
    24 static char rcsid =
    25  "@(#) $Id$";
    26 #endif
    27 
    28 /* The high-level video driver subsystem */
    29 
    30 #include <stdio.h>
    31 #include <stdlib.h>
    32 #include <string.h>
    33 
    34 #include "SDL.h"
    35 #include "SDL_error.h"
    36 #include "SDL_video.h"
    37 #include "SDL_events.h"
    38 #include "SDL_mutex.h"
    39 #include "SDL_sysvideo.h"
    40 #include "SDL_sysevents.h"
    41 #include "SDL_blit.h"
    42 #include "SDL_pixels_c.h"
    43 #include "SDL_events_c.h"
    44 #include "SDL_cursor_c.h"
    45 
    46 /* Available video drivers */
    47 static VideoBootStrap *bootstrap[] = {
    48 #ifdef ENABLE_X11
    49 	&X11_bootstrap,
    50 #endif
    51 #ifdef ENABLE_DGA
    52 	&DGA_bootstrap,
    53 #endif
    54 #ifdef ENABLE_FBCON
    55 	&FBCON_bootstrap,
    56 #endif
    57 #ifdef ENABLE_PS2GS
    58 	&PS2GS_bootstrap,
    59 #endif
    60 #ifdef ENABLE_GGI
    61 	&GGI_bootstrap,
    62 #endif
    63 #ifdef ENABLE_SVGALIB
    64 	&SVGALIB_bootstrap,
    65 #endif
    66 #ifdef ENABLE_AALIB
    67     &AALIB_bootstrap,
    68 #endif
    69 #ifdef ENABLE_DIRECTX
    70 	&DIRECTX_bootstrap,
    71 #endif
    72 #ifdef ENABLE_WINDIB
    73 	&WINDIB_bootstrap,
    74 #endif
    75 #ifdef ENABLE_BWINDOW
    76 	&BWINDOW_bootstrap,
    77 #endif
    78 #ifdef ENABLE_TOOLBOX
    79 	&TOOLBOX_bootstrap,
    80 #endif
    81 #ifdef ENABLE_DRAWSPROCKET
    82 	&DSp_bootstrap,
    83 #endif
    84 #ifdef ENABLE_CYBERGRAPHICS
    85 	&CGX_bootstrap,
    86 #endif
    87 #ifdef ENABLE_DUMMYVIDEO
    88 	&DUMMY_bootstrap,
    89 #endif
    90 	NULL
    91 };
    92 SDL_VideoDevice *current_video = NULL;
    93 
    94 /* Places to store title and icon text for the app */
    95 static char *wm_title = NULL;
    96 static char *wm_icon  = NULL;
    97 
    98 /* Various local functions */
    99 int SDL_VideoInit(const char *driver_name, Uint32 flags);
   100 void SDL_VideoQuit(void);
   101 void SDL_GL_UpdateRectsLock(SDL_VideoDevice* this, int numrects, SDL_Rect* rects);
   102 
   103 static SDL_GrabMode SDL_WM_GrabInputOff(void);
   104 #ifdef HAVE_OPENGL
   105 static int lock_count = 0;
   106 #endif
   107 
   108 
   109 /*
   110  * Initialize the video and event subsystems -- determine native pixel format
   111  */
   112 int SDL_VideoInit (const char *driver_name, Uint32 flags)
   113 {
   114 	SDL_VideoDevice *video;
   115 	int index;
   116 	int i;
   117 	SDL_PixelFormat vformat;
   118 	Uint32 video_flags;
   119 
   120 	/* Toggle the event thread flags, based on OS requirements */
   121 #if defined(MUST_THREAD_EVENTS)
   122 	flags |= SDL_INIT_EVENTTHREAD;
   123 #elif defined(CANT_THREAD_EVENTS)
   124 	if ( (flags & SDL_INIT_EVENTTHREAD) == SDL_INIT_EVENTTHREAD ) {
   125 		SDL_SetError("OS doesn't support threaded events");
   126 		return(-1);
   127 	}
   128 #endif
   129 
   130 	/* Check to make sure we don't overwrite 'current_video' */
   131 	if ( current_video != NULL ) {
   132 		SDL_VideoQuit();
   133 	}
   134 
   135 	/* Select the proper video driver */
   136 	index = 0;
   137 	video = NULL;
   138 	if ( driver_name != NULL ) {
   139 #if 0	/* This will be replaced with a better driver selection API */
   140 		if ( strrchr(driver_name, ':') != NULL ) {
   141 			index = atoi(strrchr(driver_name, ':')+1);
   142 		}
   143 #endif
   144 		for ( i=0; bootstrap[i]; ++i ) {
   145 			if ( strncmp(bootstrap[i]->name, driver_name,
   146 			             strlen(bootstrap[i]->name)) == 0 ) {
   147 				if ( bootstrap[i]->available() ) {
   148 					video = bootstrap[i]->create(index);
   149 					break;
   150 				}
   151 			}
   152 		}
   153 	} else {
   154 		for ( i=0; bootstrap[i]; ++i ) {
   155 			if ( bootstrap[i]->available() ) {
   156 				video = bootstrap[i]->create(index);
   157 				if ( video != NULL ) {
   158 					break;
   159 				}
   160 			}
   161 		}
   162 	}
   163 	if ( video == NULL ) {
   164 		SDL_SetError("No available video device");
   165 		return(-1);
   166 	}
   167 	current_video = video;
   168 	current_video->name = bootstrap[i]->name;
   169 
   170 	/* Do some basic variable initialization */
   171 	video->screen = NULL;
   172 	video->shadow = NULL;
   173 	video->visible = NULL;
   174 	video->physpal = NULL;
   175 	video->gammacols = NULL;
   176 	video->gamma = NULL;
   177 	video->wm_title = NULL;
   178 	video->wm_icon  = NULL;
   179 	video->offset_x = 0;
   180 	video->offset_y = 0;
   181 	memset(&video->info, 0, (sizeof video->info));
   182 
   183 	/* Set some very sane GL defaults */
   184 	video->gl_config.driver_loaded = 0;
   185 	video->gl_config.dll_handle = NULL;
   186 	video->gl_config.red_size = 5;
   187 #if 1 /* This seems to work on more video cards, as a default */
   188 	video->gl_config.green_size = 5;
   189 #else
   190 	video->gl_config.green_size = 6;
   191 #endif
   192 	video->gl_config.blue_size = 5;
   193 	video->gl_config.alpha_size = 0;
   194 	video->gl_config.buffer_size = 0;
   195 	video->gl_config.depth_size = 16;
   196 	video->gl_config.stencil_size = 0;
   197 	video->gl_config.double_buffer = 1;
   198 	video->gl_config.accum_red_size = 0;
   199 	video->gl_config.accum_green_size = 0;
   200 	video->gl_config.accum_blue_size = 0;
   201 	video->gl_config.accum_alpha_size = 0;
   202 	
   203 	/* Initialize the video subsystem */
   204 	memset(&vformat, 0, sizeof(vformat));
   205 	if ( video->VideoInit(video, &vformat) < 0 ) {
   206 		SDL_VideoQuit();
   207 		return(-1);
   208 	}
   209 
   210 	/* Create a zero sized video surface of the appropriate format */
   211 	video_flags = SDL_SWSURFACE;
   212 	SDL_VideoSurface = SDL_CreateRGBSurface(video_flags, 0, 0,
   213 				vformat.BitsPerPixel,
   214 				vformat.Rmask, vformat.Gmask, vformat.Bmask, 0);
   215 	if ( SDL_VideoSurface == NULL ) {
   216 		SDL_VideoQuit();
   217 		return(-1);
   218 	}
   219 	SDL_PublicSurface = NULL;	/* Until SDL_SetVideoMode() */
   220 
   221 #if 0 /* Don't change the current palette - may be used by other programs.
   222        * The application can't do anything with the display surface until
   223        * a video mode has been set anyway. :)
   224        */
   225 	/* If we have a palettized surface, create a default palette */
   226 	if ( SDL_VideoSurface->format->palette ) {
   227 	        SDL_PixelFormat *vf = SDL_VideoSurface->format;
   228 		SDL_DitherColors(vf->palette->colors, vf->BitsPerPixel);
   229 		video->SetColors(video,
   230 				 0, vf->palette->ncolors, vf->palette->colors);
   231 	}
   232 #endif
   233 	video->info.vfmt = SDL_VideoSurface->format;
   234 
   235 	/* Start the event loop */
   236 	if ( SDL_StartEventLoop(flags) < 0 ) {
   237 		SDL_VideoQuit();
   238 		return(-1);
   239 	}
   240 	SDL_CursorInit(flags & SDL_INIT_EVENTTHREAD);
   241 
   242 	/* We're ready to go! */
   243 	return(0);
   244 }
   245 
   246 char *SDL_VideoDriverName(char *namebuf, int maxlen)
   247 {
   248 	if ( current_video != NULL ) {
   249 		strncpy(namebuf, current_video->name, maxlen-1);
   250 		namebuf[maxlen-1] = '\0';
   251 		return(namebuf);
   252 	}
   253 	return(NULL);
   254 }
   255 
   256 /*
   257  * Get the current display surface
   258  */
   259 SDL_Surface *SDL_GetVideoSurface(void)
   260 {
   261 	SDL_Surface *visible;
   262 
   263 	visible = NULL;
   264 	if ( current_video ) {
   265 		visible = current_video->visible;
   266 	}
   267 	return(visible);
   268 }
   269 
   270 /*
   271  * Get the current information about the video hardware
   272  */
   273 const SDL_VideoInfo *SDL_GetVideoInfo(void)
   274 {
   275 	const SDL_VideoInfo *info;
   276 
   277 	info = NULL;
   278 	if ( current_video ) {
   279 		info = &current_video->info;
   280 	}
   281 	return(info);
   282 }
   283 
   284 /*
   285  * Return a pointer to an array of available screen dimensions for the
   286  * given format, sorted largest to smallest.  Returns NULL if there are
   287  * no dimensions available for a particular format, or (SDL_Rect **)-1
   288  * if any dimension is okay for the given format.  If 'format' is NULL,
   289  * the mode list will be for the format given by SDL_GetVideoInfo()->vfmt
   290  */
   291 SDL_Rect ** SDL_ListModes (SDL_PixelFormat *format, Uint32 flags)
   292 {
   293 	SDL_VideoDevice *video = current_video;
   294 	SDL_VideoDevice *this  = current_video;
   295 	SDL_Rect **modes;
   296 
   297 	modes = NULL;
   298 	if ( SDL_VideoSurface ) {
   299 		if ( format == NULL ) {
   300 			format = SDL_VideoSurface->format;
   301 		}
   302 		modes = video->ListModes(this, format, flags);
   303 	}
   304 	return(modes);
   305 }
   306 
   307 /*
   308  * Check to see if a particular video mode is supported.
   309  * It returns 0 if the requested mode is not supported under any bit depth,
   310  * or returns the bits-per-pixel of the closest available mode with the
   311  * given width and height.  If this bits-per-pixel is different from the
   312  * one used when setting the video mode, SDL_SetVideoMode() will succeed,
   313  * but will emulate the requested bits-per-pixel with a shadow surface.
   314  */
   315 static Uint8 SDL_closest_depths[4][8] = {
   316 	/* 8 bit closest depth ordering */
   317 	{ 0, 8, 16, 15, 32, 24, 0, 0 },
   318 	/* 15,16 bit closest depth ordering */
   319 	{ 0, 16, 15, 32, 24, 8, 0, 0 },
   320 	/* 24 bit closest depth ordering */
   321 	{ 0, 24, 32, 16, 15, 8, 0, 0 },
   322 	/* 32 bit closest depth ordering */
   323 	{ 0, 32, 16, 15, 24, 8, 0, 0 }
   324 };
   325 
   326 int SDL_VideoModeOK (int width, int height, int bpp, Uint32 flags) 
   327 {
   328 	int table, b, i;
   329 	int supported;
   330 	SDL_PixelFormat format;
   331 	SDL_Rect **sizes;
   332 
   333 	/* Currently 1 and 4 bpp are not supported */
   334 	if ( bpp < 8 || bpp > 32 ) {
   335 		return(0);
   336 	}
   337 	if ( (width == 0) || (height == 0) ) {
   338 		return(0);
   339 	}
   340 
   341 	/* Search through the list valid of modes */
   342 	memset(&format, 0, sizeof(format));
   343 	supported = 0;
   344 	table = ((bpp+7)/8)-1;
   345 	SDL_closest_depths[table][0] = bpp;
   346 	SDL_closest_depths[table][7] = 0;
   347 	for ( b = 0; !supported && SDL_closest_depths[table][b]; ++b ) {
   348 		format.BitsPerPixel = SDL_closest_depths[table][b];
   349 		sizes = SDL_ListModes(&format, flags);
   350 		if ( sizes == (SDL_Rect **)0 ) {
   351 			/* No sizes supported at this bit-depth */
   352 			continue;
   353 		} else 
   354 #ifdef macintosh /* MPW optimization bug? */
   355 		if ( (sizes == (SDL_Rect **)0xFFFFFFFF) ||
   356 #else
   357 		if ( (sizes == (SDL_Rect **)-1) ||
   358 #endif
   359 		     current_video->handles_any_size ) {
   360 			/* Any size supported at this bit-depth */
   361 			supported = 1;
   362 			continue;
   363 		} else
   364 		for ( i=0; sizes[i]; ++i ) {
   365 			if ((sizes[i]->w == width) && (sizes[i]->h == height)) {
   366 				supported = 1;
   367 				break;
   368 			}
   369 		}
   370 	}
   371 	if ( supported ) {
   372 		--b;
   373 		return(SDL_closest_depths[table][b]);
   374 	} else {
   375 		return(0);
   376 	}
   377 }
   378 
   379 /*
   380  * Get the closest non-emulated video mode to the one requested
   381  */
   382 static int SDL_GetVideoMode (int *w, int *h, int *BitsPerPixel, Uint32 flags)
   383 {
   384 	int table, b, i;
   385 	int supported;
   386 	int native_bpp;
   387 	SDL_PixelFormat format;
   388 	SDL_Rect **sizes;
   389 
   390 	/* Try the original video mode, get the closest depth */
   391 	native_bpp = SDL_VideoModeOK(*w, *h, *BitsPerPixel, flags);
   392 	if ( native_bpp == *BitsPerPixel ) {
   393 		return(1);
   394 	}
   395 	if ( native_bpp > 0 ) {
   396 		*BitsPerPixel = native_bpp;
   397 		return(1);
   398 	}
   399 
   400 	/* No exact size match at any depth, look for closest match */
   401 	memset(&format, 0, sizeof(format));
   402 	supported = 0;
   403 	table = ((*BitsPerPixel+7)/8)-1;
   404 	SDL_closest_depths[table][0] = *BitsPerPixel;
   405 	SDL_closest_depths[table][7] = SDL_VideoSurface->format->BitsPerPixel;
   406 	for ( b = 0; !supported && SDL_closest_depths[table][b]; ++b ) {
   407 		format.BitsPerPixel = SDL_closest_depths[table][b];
   408 		sizes = SDL_ListModes(&format, flags);
   409 		if ( sizes == (SDL_Rect **)0 ) {
   410 			/* No sizes supported at this bit-depth */
   411 			continue;
   412 		}
   413 		for ( i=0; sizes[i]; ++i ) {
   414 			if ((sizes[i]->w < *w) || (sizes[i]->h < *h)) {
   415 				if ( i > 0 ) {
   416 					--i;
   417 					*w = sizes[i]->w;
   418 					*h = sizes[i]->h;
   419 					*BitsPerPixel = SDL_closest_depths[table][b];
   420 					supported = 1;
   421 				} else {
   422 					/* Largest mode too small... */;
   423 				}
   424 				break;
   425 			}
   426 		}
   427 		if ( (i > 0) && ! sizes[i] ) {
   428 			/* The smallest mode was larger than requested, OK */
   429 			--i;
   430 			*w = sizes[i]->w;
   431 			*h = sizes[i]->h;
   432 			*BitsPerPixel = SDL_closest_depths[table][b];
   433 			supported = 1;
   434 		}
   435 	}
   436 	if ( ! supported ) {
   437 		SDL_SetError("No video mode large enough for %dx%d", *w, *h);
   438 	}
   439 	return(supported);
   440 }
   441 
   442 /* This should probably go somewhere else -- like SDL_surface.c */
   443 static void SDL_ClearSurface(SDL_Surface *surface)
   444 {
   445 	Uint32 black;
   446 
   447 	black = SDL_MapRGB(surface->format, 0, 0, 0);
   448 	SDL_FillRect(surface, NULL, black);
   449 	if ((surface->flags&SDL_HWSURFACE) && (surface->flags&SDL_DOUBLEBUF)) {
   450 		SDL_Flip(surface);
   451 		SDL_FillRect(surface, NULL, black);
   452 	}
   453 	SDL_Flip(surface);
   454 }
   455 
   456 /*
   457  * Create a shadow surface suitable for fooling the app. :-)
   458  */
   459 static void SDL_CreateShadowSurface(int depth)
   460 {
   461 	Uint32 Rmask, Gmask, Bmask;
   462 
   463 	/* Allocate the shadow surface */
   464 	if ( depth == (SDL_VideoSurface->format)->BitsPerPixel ) {
   465 		Rmask = (SDL_VideoSurface->format)->Rmask;
   466 		Gmask = (SDL_VideoSurface->format)->Gmask;
   467 		Bmask = (SDL_VideoSurface->format)->Bmask;
   468 	} else {
   469 		Rmask = Gmask = Bmask = 0;
   470 	}
   471 	SDL_ShadowSurface = SDL_CreateRGBSurface(SDL_SWSURFACE,
   472 				SDL_VideoSurface->w, SDL_VideoSurface->h,
   473 						depth, Rmask, Gmask, Bmask, 0);
   474 	if ( SDL_ShadowSurface == NULL ) {
   475 		return;
   476 	}
   477 
   478 	/* 8-bit shadow surfaces report that they have exclusive palette */
   479 	if ( SDL_ShadowSurface->format->palette ) {
   480 		SDL_ShadowSurface->flags |= SDL_HWPALETTE;
   481 		if ( depth == (SDL_VideoSurface->format)->BitsPerPixel ) {
   482 			memcpy(SDL_ShadowSurface->format->palette->colors,
   483 				SDL_VideoSurface->format->palette->colors,
   484 				SDL_VideoSurface->format->palette->ncolors*
   485 							sizeof(SDL_Color));
   486 		} else {
   487 			SDL_DitherColors(
   488 			SDL_ShadowSurface->format->palette->colors, depth);
   489 		}
   490 	}
   491 
   492 	/* If the video surface is resizable, the shadow should say so */
   493 	if ( (SDL_VideoSurface->flags & SDL_RESIZABLE) == SDL_RESIZABLE ) {
   494 		SDL_ShadowSurface->flags |= SDL_RESIZABLE;
   495 	}
   496 	/* If the video surface has no frame, the shadow should say so */
   497 	if ( (SDL_VideoSurface->flags & SDL_NOFRAME) == SDL_NOFRAME ) {
   498 		SDL_ShadowSurface->flags |= SDL_NOFRAME;
   499 	}
   500 	/* If the video surface is fullscreen, the shadow should say so */
   501 	if ( (SDL_VideoSurface->flags & SDL_FULLSCREEN) == SDL_FULLSCREEN ) {
   502 		SDL_ShadowSurface->flags |= SDL_FULLSCREEN;
   503 	}
   504 	/* If the video surface is flippable, the shadow should say so */
   505 	if ( (SDL_VideoSurface->flags & SDL_DOUBLEBUF) == SDL_DOUBLEBUF ) {
   506 		SDL_ShadowSurface->flags |= SDL_DOUBLEBUF;
   507 	}
   508 	return;
   509 }
   510 
   511 /*
   512  * Set the requested video mode, allocating a shadow buffer if necessary.
   513  */
   514 SDL_Surface * SDL_SetVideoMode (int width, int height, int bpp, Uint32 flags)
   515 {
   516 	SDL_VideoDevice *video, *this;
   517 	SDL_Surface *prev_mode, *mode;
   518 	int video_w;
   519 	int video_h;
   520 	int video_bpp;
   521 	int is_opengl;
   522 	SDL_GrabMode saved_grab;
   523 
   524 	/* Start up the video driver, if necessary..
   525 	   WARNING: This is the only function protected this way!
   526 	 */
   527 	if ( ! current_video ) {
   528 		if ( SDL_Init(SDL_INIT_VIDEO|SDL_INIT_NOPARACHUTE) < 0 ) {
   529 			return(NULL);
   530 		}
   531 	}
   532 	this = video = current_video;
   533 
   534 	/* Default to the current video bpp */
   535 	if ( bpp == 0 ) {
   536 		flags |= SDL_ANYFORMAT;
   537 		bpp = SDL_VideoSurface->format->BitsPerPixel;
   538 	}
   539 
   540 	/* Get a good video mode, the closest one possible */
   541 	video_w = width;
   542 	video_h = height;
   543 	video_bpp = bpp;
   544 	if ( ! SDL_GetVideoMode(&video_w, &video_h, &video_bpp, flags) ) {
   545 		return(NULL);
   546 	}
   547 
   548 	/* Check the requested flags */
   549 	/* There's no palette in > 8 bits-per-pixel mode */
   550 	if ( video_bpp > 8 ) {
   551 		flags &= ~SDL_HWPALETTE;
   552 	}
   553 #if 0
   554 	if ( (flags&SDL_FULLSCREEN) != SDL_FULLSCREEN ) {
   555 		/* There's no windowed double-buffering */
   556 		flags &= ~SDL_DOUBLEBUF;
   557 	}
   558 #endif
   559 	if ( (flags&SDL_DOUBLEBUF) == SDL_DOUBLEBUF ) {
   560 		/* Use hardware surfaces when double-buffering */
   561 		flags |= SDL_HWSURFACE;
   562 	}
   563 
   564 	is_opengl = ( ( flags & SDL_OPENGL ) == SDL_OPENGL );
   565 	if ( is_opengl ) {
   566 		/* These flags are for 2D video modes only */
   567 		flags &= ~(SDL_HWSURFACE|SDL_DOUBLEBUF);
   568 	}
   569 
   570 	/* Reset the keyboard here so event callbacks can run */
   571 	SDL_ResetKeyboard();
   572 
   573 	/* Clean up any previous video mode */
   574 	if ( SDL_PublicSurface != NULL ) {
   575 		SDL_PublicSurface = NULL;
   576 	}
   577 	if ( SDL_ShadowSurface != NULL ) {
   578 		SDL_Surface *ready_to_go;
   579 		ready_to_go = SDL_ShadowSurface;
   580 		SDL_ShadowSurface = NULL;
   581 		SDL_FreeSurface(ready_to_go);
   582 	}
   583 	if ( video->physpal ) {
   584 		free(video->physpal->colors);
   585 		free(video->physpal);
   586 		video->physpal = NULL;
   587 	}
   588 	if( video->gammacols) {
   589 	        free(video->gammacols);
   590 		video->gammacols = NULL;
   591 	}
   592 
   593 	/* Save the previous grab state and turn off grab for mode switch */
   594 	saved_grab = SDL_WM_GrabInputOff();
   595 
   596 	/* Try to set the video mode, along with offset and clipping */
   597 	prev_mode = SDL_VideoSurface;
   598 	SDL_LockCursor();
   599 	SDL_VideoSurface = NULL;	/* In case it's freed by driver */
   600 	mode = video->SetVideoMode(this, prev_mode,video_w,video_h,video_bpp,flags);
   601 	if ( mode ) { /* Prevent resize events from mode change */
   602 	    SDL_PrivateResize(mode->w, mode->h);
   603         }
   604 	/*
   605 	 * rcg11292000
   606 	 * If you try to set an SDL_OPENGL surface, and fail to find a
   607 	 * matching  visual, then the next call to SDL_SetVideoMode()
   608 	 * will segfault, since  we no longer point to a dummy surface,
   609 	 * but rather NULL.
   610 	 * Sam 11/29/00
   611 	 * WARNING, we need to make sure that the previous mode hasn't
   612 	 * already been freed by the video driver.  What do we do in
   613 	 * that case?  Should we call SDL_VideoInit() again?
   614 	 */
   615 	SDL_VideoSurface = (mode != NULL) ? mode : prev_mode;
   616 
   617 	if ( (mode != NULL) && (!is_opengl) ) {
   618 		/* Sanity check */
   619 		if ( (mode->w < width) || (mode->h < height) ) {
   620 			SDL_SetError("Video mode smaller than requested");
   621 			return(NULL);
   622 		}
   623 
   624 		/* If we have a palettized surface, create a default palette */
   625 		if ( mode->format->palette ) {
   626 	        	SDL_PixelFormat *vf = mode->format;
   627 			SDL_DitherColors(vf->palette->colors, vf->BitsPerPixel);
   628 			video->SetColors(this, 0, vf->palette->ncolors,
   629 			                           vf->palette->colors);
   630 		}
   631 
   632 		/* Clear the surface to black */
   633 		video->offset_x = 0;
   634 		video->offset_y = 0;
   635 		mode->offset = 0;
   636 		SDL_SetClipRect(mode, NULL);
   637 		SDL_ClearSurface(mode);
   638 
   639 		/* Now adjust the offsets to match the desired mode */
   640 		video->offset_x = (mode->w-width)/2;
   641 		video->offset_y = (mode->h-height)/2;
   642 		mode->offset = video->offset_y*mode->pitch +
   643 				video->offset_x*mode->format->BytesPerPixel;
   644 #ifdef DEBUG_VIDEO
   645   fprintf(stderr,
   646 	"Requested mode: %dx%dx%d, obtained mode %dx%dx%d (offset %d)\n",
   647 		width, height, bpp,
   648 		mode->w, mode->h, mode->format->BitsPerPixel, mode->offset);
   649 #endif
   650 		mode->w = width;
   651 		mode->h = height;
   652 		SDL_SetClipRect(mode, NULL);
   653 	}
   654 	SDL_ResetCursor();
   655 	SDL_UnlockCursor();
   656 
   657 	/* If we failed setting a video mode, return NULL... (Uh Oh!) */
   658 	if ( mode == NULL ) {
   659 		return(NULL);
   660 	}
   661 
   662 	/* If there is no window manager, set the SDL_NOFRAME flag */
   663 	if ( ! video->info.wm_available ) {
   664 		mode->flags |= SDL_NOFRAME;
   665 	}
   666 
   667 	/* Reset the mouse cursor and grab for new video mode */
   668 	SDL_SetCursor(NULL);
   669 	if ( video->UpdateMouse ) {
   670 		video->UpdateMouse(this);
   671 	}
   672 	SDL_WM_GrabInput(saved_grab);
   673 	SDL_GetRelativeMouseState(NULL, NULL); /* Clear first large delta */
   674 
   675 	/* If we're running OpenGL, make the context current */
   676 	if ( (video->screen->flags & SDL_OPENGL) &&
   677 	      video->GL_MakeCurrent ) {
   678 		if ( video->GL_MakeCurrent(this) < 0 ) {
   679 			return(NULL);
   680 		}
   681 	}
   682 
   683 	/* Set up a fake SDL surface for OpenGL "blitting" */
   684 	if ( (flags & SDL_OPENGLBLIT) == SDL_OPENGLBLIT ) {
   685 		/* Load GL functions for performing the texture updates */
   686 #ifdef HAVE_OPENGL
   687 #define SDL_PROC(ret,func,params) \
   688 do { \
   689 	video->func = SDL_GL_GetProcAddress(#func); \
   690 	if ( ! video->func ) { \
   691 		SDL_SetError("Couldn't load GL function: %s\n", #func); \
   692 		return(NULL); \
   693 	} \
   694 } while ( 0 );
   695 #include "SDL_glfuncs.h"
   696 #undef SDL_PROC	
   697 
   698 		/* Create a software surface for blitting */
   699 #ifdef GL_VERSION_1_2
   700 		/* If the implementation either supports the packed pixels
   701 		   extension, or implements the core OpenGL 1.2 API, it will
   702 		   support the GL_UNSIGNED_SHORT_5_6_5 texture format.
   703 		 */
   704 		if ( (bpp == 16) &&
   705 		     (strstr((const char *)video->glGetString(GL_EXTENSIONS),
   706 		                           "GL_EXT_packed_pixels") ||
   707 		     (strncmp((const char *)video->glGetString(GL_VERSION),
   708 		              "1.2", 3) == 0)) )
   709 		{
   710 			video->is_32bit = 0;
   711 			SDL_VideoSurface = SDL_CreateRGBSurface(
   712 				flags, 
   713 				width, 
   714 				height,  
   715 				16,
   716 				31 << 11,
   717 				63 << 5,
   718 				31,
   719 				0
   720 				);
   721 		}
   722 		else
   723 #endif /* OpenGL 1.2 */
   724 		{
   725 			video->is_32bit = 1;
   726 			SDL_VideoSurface = SDL_CreateRGBSurface(
   727 				flags, 
   728 				width, 
   729 				height, 
   730 				32, 
   731 #if SDL_BYTEORDER == SDL_LIL_ENDIAN
   732 				0x000000FF,
   733 				0x0000FF00,
   734 				0x00FF0000,
   735 				0xFF000000
   736 #else
   737 				0xFF000000,
   738 				0x00FF0000,
   739 				0x0000FF00,
   740 				0x000000FF
   741 #endif
   742 				);
   743 		}
   744 		if ( ! SDL_VideoSurface ) {
   745 			return(NULL);
   746 		}
   747 		SDL_VideoSurface->flags = mode->flags | SDL_OPENGLBLIT;
   748 
   749 		/* Free the original video mode surface (is this safe?) */
   750 		SDL_FreeSurface(mode);
   751 
   752                 /* Set the surface completely opaque & white by default */
   753 		memset( SDL_VideoSurface->pixels, 255, SDL_VideoSurface->h * SDL_VideoSurface->pitch );
   754 		video->glGenTextures( 1, &video->texture );
   755 		video->glBindTexture( GL_TEXTURE_2D, video->texture );
   756 		video->glTexImage2D(
   757 			GL_TEXTURE_2D,
   758 			0,
   759 			video->is_32bit ? GL_RGBA : GL_RGB,
   760 			256,
   761 			256,
   762 			0,
   763 			video->is_32bit ? GL_RGBA : GL_RGB,
   764 #ifdef GL_VERSION_1_2
   765 			video->is_32bit ? GL_UNSIGNED_BYTE : GL_UNSIGNED_SHORT_5_6_5,
   766 #else
   767 			GL_UNSIGNED_BYTE,
   768 #endif
   769 			NULL);
   770 
   771 		video->UpdateRects = SDL_GL_UpdateRectsLock;
   772 #else
   773 		SDL_SetError("Somebody forgot to #define HAVE_OPENGL");
   774 		return(NULL);
   775 #endif
   776 	}
   777 
   778 	/* Create a shadow surface if necessary */
   779 	/* There are three conditions under which we create a shadow surface:
   780 		1.  We need a particular bits-per-pixel that we didn't get.
   781 		2.  We need a hardware palette and didn't get one.
   782 		3.  We need a software surface and got a hardware surface.
   783 	*/
   784 	if ( !(SDL_VideoSurface->flags & SDL_OPENGL) &&
   785 	     (
   786 	     (  !(flags&SDL_ANYFORMAT) &&
   787 			(SDL_VideoSurface->format->BitsPerPixel != bpp)) ||
   788 	     (   (flags&SDL_HWPALETTE) && 
   789 				!(SDL_VideoSurface->flags&SDL_HWPALETTE)) ||
   790 		/* If the surface is in hardware, video writes are visible
   791 		   as soon as they are performed, so we need to buffer them
   792 		 */
   793 	     (   ((flags&SDL_HWSURFACE) == SDL_SWSURFACE) &&
   794 				(SDL_VideoSurface->flags&SDL_HWSURFACE))
   795 	     ) ) {
   796 		SDL_CreateShadowSurface(bpp);
   797 		if ( SDL_ShadowSurface == NULL ) {
   798 			SDL_SetError("Couldn't create shadow surface");
   799 			return(NULL);
   800 		}
   801 		SDL_PublicSurface = SDL_ShadowSurface;
   802 	} else {
   803 		SDL_PublicSurface = SDL_VideoSurface;
   804 	}
   805 	video->info.vfmt = SDL_VideoSurface->format;
   806 
   807 	/* We're done! */
   808 	return(SDL_PublicSurface);
   809 }
   810 
   811 /* 
   812  * Convert a surface into the video pixel format.
   813  */
   814 SDL_Surface * SDL_DisplayFormat (SDL_Surface *surface)
   815 {
   816 	Uint32 flags;
   817 
   818 	if ( ! SDL_PublicSurface ) {
   819 		SDL_SetError("No video mode has been set");
   820 		return(NULL);
   821 	}
   822 	/* Set the flags appropriate for copying to display surface */
   823 	flags  = (SDL_PublicSurface->flags&SDL_HWSURFACE);
   824 #ifdef AUTORLE_DISPLAYFORMAT
   825 	flags |= (surface->flags & (SDL_SRCCOLORKEY|SDL_SRCALPHA));
   826 	flags |= SDL_RLEACCELOK;
   827 #else
   828 	flags |= surface->flags & (SDL_SRCCOLORKEY|SDL_SRCALPHA|SDL_RLEACCELOK);
   829 #endif
   830 	return(SDL_ConvertSurface(surface, SDL_PublicSurface->format, flags));
   831 }
   832 
   833 /*
   834  * Convert a surface into a format that's suitable for blitting to
   835  * the screen, but including an alpha channel.
   836  */
   837 SDL_Surface *SDL_DisplayFormatAlpha(SDL_Surface *surface)
   838 {
   839 	SDL_PixelFormat *vf;
   840 	SDL_PixelFormat *format;
   841 	SDL_Surface *converted;
   842 	Uint32 flags;
   843 	/* default to ARGB8888 */
   844 	Uint32 amask = 0xff000000;
   845 	Uint32 rmask = 0x00ff0000;
   846 	Uint32 gmask = 0x0000ff00;
   847 	Uint32 bmask = 0x000000ff;
   848 
   849 	if ( ! SDL_PublicSurface ) {
   850 		SDL_SetError("No video mode has been set");
   851 		return(NULL);
   852 	}
   853 	vf = SDL_PublicSurface->format;
   854 
   855 	switch(vf->BytesPerPixel) {
   856 	    case 2:
   857 		/* For XGY5[56]5, use, AXGY8888, where {X, Y} = {R, B}.
   858 		   For anything else (like ARGB4444) it doesn't matter
   859 		   since we have no special code for it anyway */
   860 		if ( (vf->Rmask == 0x1f) &&
   861 		     (vf->Bmask == 0xf800 || vf->Bmask == 0x7c00)) {
   862 			rmask = 0xff;
   863 			bmask = 0xff0000;
   864 		}
   865 		break;
   866 
   867 	    case 3:
   868 	    case 4:
   869 		/* Keep the video format, as long as the high 8 bits are
   870 		   unused or alpha */
   871 		if ( (vf->Rmask == 0xff) && (vf->Bmask == 0xff0000) ) {
   872 			rmask = 0xff;
   873 			bmask = 0xff0000;
   874 		}
   875 		break;
   876 
   877 	    default:
   878 		/* We have no other optimised formats right now. When/if a new
   879 		   optimised alpha format is written, add the converter here */
   880 		break;
   881 	}
   882 	format = SDL_AllocFormat(32, rmask, gmask, bmask, amask);
   883 	flags = SDL_PublicSurface->flags & SDL_HWSURFACE;
   884 	flags |= surface->flags & (SDL_SRCALPHA | SDL_RLEACCELOK);
   885 	converted = SDL_ConvertSurface(surface, format, flags);
   886 	SDL_FreeFormat(format);
   887 	return(converted);
   888 }
   889 
   890 /*
   891  * Update a specific portion of the physical screen
   892  */
   893 void SDL_UpdateRect(SDL_Surface *screen, Sint32 x, Sint32 y, Uint32 w, Uint32 h)
   894 {
   895 	if ( screen ) {
   896 		SDL_Rect rect;
   897 
   898 		/* Perform some checking */
   899 		if ( w == 0 )
   900 			w = screen->w;
   901 		if ( h == 0 )
   902 			h = screen->h;
   903 		if ( (int)(x+w) > screen->w )
   904 			return;
   905 		if ( (int)(y+h) > screen->h )
   906 			return;
   907 
   908 		/* Fill the rectangle */
   909 		rect.x = x;
   910 		rect.y = y;
   911 		rect.w = w;
   912 		rect.h = h;
   913 		SDL_UpdateRects(screen, 1, &rect);
   914 	}
   915 }
   916 void SDL_UpdateRects (SDL_Surface *screen, int numrects, SDL_Rect *rects)
   917 {
   918 	int i;
   919 	SDL_VideoDevice *video = current_video;
   920 	SDL_VideoDevice *this = current_video;
   921 
   922 	if ( screen == SDL_ShadowSurface ) {
   923 		/* Blit the shadow surface using saved mapping */
   924 	        SDL_Palette *pal = screen->format->palette;
   925 		SDL_Color *saved_colors = NULL;
   926 	        if ( pal && !(SDL_VideoSurface->flags & SDL_HWPALETTE) ) {
   927 			/* simulated 8bpp, use correct physical palette */
   928 			saved_colors = pal->colors;
   929 			if ( video->gammacols ) {
   930 				/* gamma-corrected palette */
   931 				pal->colors = video->gammacols;
   932 			} else if ( video->physpal ) {
   933 				/* physical palette different from logical */
   934 				pal->colors = video->physpal->colors;
   935 			}
   936 		}
   937 		if ( SHOULD_DRAWCURSOR(SDL_cursorstate) ) {
   938 			SDL_LockCursor();
   939 			SDL_DrawCursor(SDL_ShadowSurface);
   940 			for ( i=0; i<numrects; ++i ) {
   941 				SDL_LowerBlit(SDL_ShadowSurface, &rects[i], 
   942 						SDL_VideoSurface, &rects[i]);
   943 			}
   944 			SDL_EraseCursor(SDL_ShadowSurface);
   945 			SDL_UnlockCursor();
   946 		} else {
   947 			for ( i=0; i<numrects; ++i ) {
   948 				SDL_LowerBlit(SDL_ShadowSurface, &rects[i], 
   949 						SDL_VideoSurface, &rects[i]);
   950 			}
   951 		}
   952 		if ( saved_colors )
   953 			pal->colors = saved_colors;
   954 
   955 		/* Fall through to video surface update */
   956 		screen = SDL_VideoSurface;
   957 	}
   958 	if ( screen == SDL_VideoSurface ) {
   959 		/* Update the video surface */
   960 		if ( screen->offset ) {
   961 			for ( i=0; i<numrects; ++i ) {
   962 				rects[i].x += video->offset_x;
   963 				rects[i].y += video->offset_y;
   964 			}
   965 			video->UpdateRects(this, numrects, rects);
   966 			for ( i=0; i<numrects; ++i ) {
   967 				rects[i].x -= video->offset_x;
   968 				rects[i].y -= video->offset_y;
   969 			}
   970 		} else {
   971 			video->UpdateRects(this, numrects, rects);
   972 		}
   973 	}
   974 }
   975 
   976 /*
   977  * Performs hardware double buffering, if possible, or a full update if not.
   978  */
   979 int SDL_Flip(SDL_Surface *screen)
   980 {
   981 	SDL_VideoDevice *video = current_video;
   982 	/* Copy the shadow surface to the video surface */
   983 	if ( screen == SDL_ShadowSurface ) {
   984 		SDL_Rect rect;
   985 	        SDL_Palette *pal = screen->format->palette;
   986 		SDL_Color *saved_colors = NULL;
   987 	        if ( pal && !(SDL_VideoSurface->flags & SDL_HWPALETTE) ) {
   988 			/* simulated 8bpp, use correct physical palette */
   989 			saved_colors = pal->colors;
   990 			if ( video->gammacols ) {
   991 				/* gamma-corrected palette */
   992 				pal->colors = video->gammacols;
   993 			} else if ( video->physpal ) {
   994 				/* physical palette different from logical */
   995 				pal->colors = video->physpal->colors;
   996 			}
   997 		}
   998 
   999 		rect.x = 0;
  1000 		rect.y = 0;
  1001 		rect.w = screen->w;
  1002 		rect.h = screen->h;
  1003 		SDL_LowerBlit(SDL_ShadowSurface,&rect, SDL_VideoSurface,&rect);
  1004 
  1005 		if ( saved_colors )
  1006 			pal->colors = saved_colors;
  1007 		screen = SDL_VideoSurface;
  1008 	}
  1009 	if ( (screen->flags & SDL_DOUBLEBUF) == SDL_DOUBLEBUF ) {
  1010 		SDL_VideoDevice *this  = current_video;
  1011 		return(video->FlipHWSurface(this, SDL_VideoSurface));
  1012 	} else {
  1013 		SDL_UpdateRect(screen, 0, 0, 0, 0);
  1014 	}
  1015 	return(0);
  1016 }
  1017 
  1018 static void SetPalette_logical(SDL_Surface *screen, SDL_Color *colors,
  1019 			       int firstcolor, int ncolors)
  1020 {
  1021         SDL_Palette *pal = screen->format->palette;
  1022 	SDL_Palette *vidpal;
  1023 
  1024 	if ( colors != (pal->colors + firstcolor) ) {
  1025 	        memcpy(pal->colors + firstcolor, colors,
  1026 		       ncolors * sizeof(*colors));
  1027 	}
  1028 
  1029 	vidpal = SDL_VideoSurface->format->palette;
  1030 	if ( (screen == SDL_ShadowSurface) && vidpal ) {
  1031 	        /*
  1032 		 * This is a shadow surface, and the physical
  1033 		 * framebuffer is also indexed. Propagate the
  1034 		 * changes to its logical palette so that
  1035 		 * updates are always identity blits
  1036 		 */
  1037 		memcpy(vidpal->colors + firstcolor, colors,
  1038 		       ncolors * sizeof(*colors));
  1039 	}
  1040 	SDL_FormatChanged(screen);
  1041 }
  1042 
  1043 static int SetPalette_physical(SDL_Surface *screen,
  1044                                SDL_Color *colors, int firstcolor, int ncolors)
  1045 {
  1046 	SDL_VideoDevice *video = current_video;
  1047 	int gotall = 1;
  1048 
  1049 	if ( video->physpal ) {
  1050 		/* We need to copy the new colors, since we haven't
  1051 		 * already done the copy in the logical set above.
  1052 		 */
  1053 		memcpy(video->physpal->colors + firstcolor,
  1054 		       colors, ncolors * sizeof(*colors));
  1055 	}
  1056 	if ( screen == SDL_ShadowSurface ) {
  1057 		if ( SDL_VideoSurface->flags & SDL_HWPALETTE ) {
  1058 			/*
  1059 			 * The real screen is also indexed - set its physical
  1060 			 * palette. The physical palette does not include the
  1061 			 * gamma modification, we apply it directly instead,
  1062 			 * but this only happens if we have hardware palette.
  1063 			 */
  1064 			screen = SDL_VideoSurface;
  1065 		} else {
  1066 			/*
  1067 			 * The video surface is not indexed - invalidate any
  1068 			 * active shadow-to-video blit mappings.
  1069 			 */
  1070 			if ( screen->map->dst == SDL_VideoSurface ) {
  1071 				SDL_InvalidateMap(screen->map);
  1072 			}
  1073 			if ( video->gamma ) {
  1074 				if( ! video->gammacols ) {
  1075 					SDL_Palette *pp = video->physpal;
  1076 					if(!pp)
  1077 						pp = screen->format->palette;
  1078 					video->gammacols = malloc(pp->ncolors
  1079 							  * sizeof(SDL_Color));
  1080 					SDL_ApplyGamma(video->gamma,
  1081 						       pp->colors,
  1082 						       video->gammacols,
  1083 						       pp->ncolors);
  1084 				} else {
  1085 					SDL_ApplyGamma(video->gamma, colors,
  1086 						       video->gammacols
  1087 						       + firstcolor,
  1088 						       ncolors);
  1089 				}
  1090 			}
  1091 			SDL_UpdateRect(screen, 0, 0, 0, 0);
  1092 		}
  1093 	}
  1094 
  1095 	if ( screen == SDL_VideoSurface ) {
  1096 		SDL_Color gcolors[256];
  1097 
  1098 	        if ( video->gamma ) {
  1099 		        SDL_ApplyGamma(video->gamma, colors, gcolors, ncolors);
  1100 			colors = gcolors;
  1101 		}
  1102 		gotall = video->SetColors(video, firstcolor, ncolors, colors);
  1103 		if ( ! gotall ) {
  1104 			/* The video flags shouldn't have SDL_HWPALETTE, and
  1105 			   the video driver is responsible for copying back the
  1106 			   correct colors into the video surface palette.
  1107 			*/
  1108 			;
  1109 		}
  1110 		SDL_CursorPaletteChanged();
  1111 	}
  1112 	return gotall;
  1113 }
  1114 
  1115 /*
  1116  * Set the physical and/or logical colormap of a surface:
  1117  * Only the screen has a physical colormap. It determines what is actually
  1118  * sent to the display.
  1119  * The logical colormap is used to map blits to/from the surface.
  1120  * 'which' is one or both of SDL_LOGPAL, SDL_PHYSPAL
  1121  *
  1122  * Return nonzero if all colours were set as requested, or 0 otherwise.
  1123  */
  1124 int SDL_SetPalette(SDL_Surface *screen, int which,
  1125 		   SDL_Color *colors, int firstcolor, int ncolors)
  1126 {
  1127         SDL_Palette *pal;
  1128 	int gotall;
  1129 	int palsize;
  1130 
  1131 	if ( screen != SDL_PublicSurface ) {
  1132 	        /* only screens have physical palettes */
  1133 	        which &= ~SDL_PHYSPAL;
  1134 	} else if( (screen->flags & SDL_HWPALETTE) != SDL_HWPALETTE ) {
  1135 	        /* hardware palettes required for split colormaps */
  1136 	        which |= SDL_PHYSPAL | SDL_LOGPAL;
  1137 	}
  1138 
  1139 	/* Verify the parameters */
  1140 	pal = screen->format->palette;
  1141 	if( !pal ) {
  1142 	        return 0;	/* not a palettized surface */
  1143 	}
  1144 	gotall = 1;
  1145 	palsize = 1 << screen->format->BitsPerPixel;
  1146 	if ( ncolors > (palsize - firstcolor) ) {
  1147 	        ncolors = (palsize - firstcolor);
  1148 		gotall = 0;
  1149 	}
  1150 
  1151 	if ( which & SDL_LOGPAL ) {
  1152 		/*
  1153 		 * Logical palette change: The actual screen isn't affected,
  1154 		 * but the internal colormap is altered so that the
  1155 		 * interpretation of the pixel values (for blits etc) is
  1156 		 * changed.
  1157 		 */
  1158 	        SetPalette_logical(screen, colors, firstcolor, ncolors);
  1159 	}
  1160 	if ( which & SDL_PHYSPAL ) {
  1161 		SDL_VideoDevice *video = current_video;
  1162 	        /*
  1163 		 * Physical palette change: This doesn't affect the
  1164 		 * program's idea of what the screen looks like, but changes
  1165 		 * its actual appearance.
  1166 		 */
  1167 	        if(!video)
  1168 		        return gotall;	/* video not yet initialized */
  1169 		if(!video->physpal && !(which & SDL_LOGPAL) ) {
  1170 			/* Lazy physical palette allocation */
  1171 		        int size;
  1172 			SDL_Palette *pp = malloc(sizeof(*pp));
  1173 			current_video->physpal = pp;
  1174 			pp->ncolors = pal->ncolors;
  1175 			size = pp->ncolors * sizeof(SDL_Color);
  1176 			pp->colors = malloc(size);
  1177 			memcpy(pp->colors, pal->colors, size);
  1178 		}
  1179 		if ( ! SetPalette_physical(screen,
  1180 		                           colors, firstcolor, ncolors) ) {
  1181 			gotall = 0;
  1182 		}
  1183 	}
  1184 	return gotall;
  1185 }
  1186 
  1187 int SDL_SetColors(SDL_Surface *screen, SDL_Color *colors, int firstcolor,
  1188 		  int ncolors)
  1189 {
  1190         return SDL_SetPalette(screen, SDL_LOGPAL | SDL_PHYSPAL,
  1191 			      colors, firstcolor, ncolors);
  1192 }
  1193 
  1194 /*
  1195  * Clean up the video subsystem
  1196  */
  1197 void SDL_VideoQuit (void)
  1198 {
  1199 	SDL_Surface *ready_to_go;
  1200 
  1201 	if ( current_video ) {
  1202 		SDL_VideoDevice *video = current_video;
  1203 		SDL_VideoDevice *this  = current_video;
  1204 
  1205 		/* Halt event processing before doing anything else */
  1206 		SDL_StopEventLoop();
  1207 
  1208 		/* Clean up allocated window manager items */
  1209 		if ( SDL_PublicSurface ) {
  1210 			SDL_PublicSurface = NULL;
  1211 		}
  1212 		SDL_CursorQuit();
  1213 
  1214 		/* Just in case... */
  1215 		SDL_WM_GrabInputOff();
  1216 
  1217 		/* Clean up the system video */
  1218 		video->VideoQuit(this);
  1219 
  1220 		/* Free any lingering surfaces */
  1221 		ready_to_go = SDL_ShadowSurface;
  1222 		SDL_ShadowSurface = NULL;
  1223 		SDL_FreeSurface(ready_to_go);
  1224 		if ( SDL_VideoSurface != NULL ) {
  1225 			ready_to_go = SDL_VideoSurface;
  1226 			SDL_VideoSurface = NULL;
  1227 			SDL_FreeSurface(ready_to_go);
  1228 		}
  1229 		SDL_PublicSurface = NULL;
  1230 
  1231 		/* Clean up miscellaneous memory */
  1232 		if ( video->physpal ) {
  1233 			free(video->physpal->colors);
  1234 			free(video->physpal);
  1235 			video->physpal = NULL;
  1236 		}
  1237 		if ( video->gammacols ) {
  1238 			free(video->gammacols);
  1239 			video->gammacols = NULL;
  1240 		}
  1241 		if ( video->gamma ) {
  1242 			free(video->gamma);
  1243 			video->gamma = NULL;
  1244 		}
  1245 		if ( wm_title != NULL ) {
  1246 			free(wm_title);
  1247 			wm_title = NULL;
  1248 		}
  1249 		if ( wm_icon != NULL ) {
  1250 			free(wm_icon);
  1251 			wm_icon = NULL;
  1252 		}
  1253 
  1254 		/* Finish cleaning up video subsystem */
  1255 		video->free(this);
  1256 		current_video = NULL;
  1257 	}
  1258 	return;
  1259 }
  1260 
  1261 /* Load the GL driver library */
  1262 int SDL_GL_LoadLibrary(const char *path)
  1263 {
  1264 	SDL_VideoDevice *video = current_video;
  1265 	SDL_VideoDevice *this = current_video;
  1266 	int retval;
  1267 
  1268 	retval = -1;
  1269 	if ( video && video->GL_LoadLibrary ) {
  1270 		retval = video->GL_LoadLibrary(this, path);
  1271 	} else {
  1272 		SDL_SetError("No dynamic GL support in video driver");
  1273 	}
  1274 	return(retval);
  1275 }
  1276 
  1277 void *SDL_GL_GetProcAddress(const char* proc)
  1278 {
  1279 	SDL_VideoDevice *video = current_video;
  1280 	SDL_VideoDevice *this = current_video;
  1281 	void *func;
  1282 
  1283 	func = NULL;
  1284 	if ( video->GL_GetProcAddress ) {
  1285 		if ( video->gl_config.driver_loaded ) {
  1286 			func = video->GL_GetProcAddress(this, proc);
  1287 		} else {
  1288 			SDL_SetError("No GL driver has been loaded");
  1289 		}
  1290 	} else {
  1291 		SDL_SetError("No dynamic GL support in video driver");
  1292 	}
  1293 	return func;
  1294 }
  1295 
  1296 /* Set the specified GL attribute for setting up a GL video mode */
  1297 int SDL_GL_SetAttribute( SDL_GLattr attr, int value )
  1298 {
  1299 	int retval;
  1300 	SDL_VideoDevice *video = current_video;
  1301 
  1302 	retval = 0;
  1303 	switch (attr) {
  1304 		case SDL_GL_RED_SIZE:
  1305 			video->gl_config.red_size = value;
  1306 			break;
  1307 		case SDL_GL_GREEN_SIZE:
  1308 			video->gl_config.green_size = value;
  1309 			break;
  1310 		case SDL_GL_BLUE_SIZE:
  1311 			video->gl_config.blue_size = value;
  1312 			break;
  1313 		case SDL_GL_ALPHA_SIZE:
  1314 			video->gl_config.alpha_size = value;
  1315 			break;
  1316 		case SDL_GL_DOUBLEBUFFER:
  1317 			video->gl_config.double_buffer = value;
  1318 			break;
  1319         	case SDL_GL_BUFFER_SIZE:
  1320 	        	video->gl_config.buffer_size = value;
  1321 			break;
  1322 		case SDL_GL_DEPTH_SIZE:
  1323 			video->gl_config.depth_size = value;
  1324 			break;
  1325 		case SDL_GL_STENCIL_SIZE:
  1326 			video->gl_config.stencil_size = value;
  1327 			break;
  1328 	        case SDL_GL_ACCUM_RED_SIZE:
  1329 			video->gl_config.accum_red_size = value;
  1330 			break;
  1331 	        case SDL_GL_ACCUM_GREEN_SIZE:
  1332 			video->gl_config.accum_green_size = value;
  1333 			break;
  1334 	        case SDL_GL_ACCUM_BLUE_SIZE:
  1335 			video->gl_config.accum_blue_size = value;
  1336 			break;
  1337 	        case SDL_GL_ACCUM_ALPHA_SIZE:
  1338 			video->gl_config.accum_alpha_size = value;
  1339 			break;
  1340 		default:
  1341 			SDL_SetError("Unknown OpenGL attribute");
  1342 			retval = -1;
  1343 			break;
  1344 	}
  1345 	return(retval);
  1346 }
  1347 
  1348 /* Retrieve an attribute value from the windowing system. */
  1349 int SDL_GL_GetAttribute(SDL_GLattr attr, int* value)
  1350 {
  1351 	int retval = -1;
  1352 	SDL_VideoDevice* video = current_video;
  1353 	SDL_VideoDevice* this = current_video;
  1354 
  1355 	if ( video->GL_GetAttribute ) {
  1356 		retval = this->GL_GetAttribute(this, attr, value);
  1357 	} else {
  1358 		*value = 0;
  1359 		SDL_SetError("GL_GetAttribute not supported");
  1360 	}
  1361 	return retval;
  1362 }
  1363 
  1364 /* Perform a GL buffer swap on the current GL context */
  1365 void SDL_GL_SwapBuffers(void)
  1366 {
  1367 	SDL_VideoDevice *video = current_video;
  1368 	SDL_VideoDevice *this = current_video;
  1369 
  1370 	if ( video->screen->flags & SDL_OPENGL ) {
  1371 		video->GL_SwapBuffers( this );
  1372 	}
  1373 }
  1374 
  1375 /* Update rects with locking */
  1376 void SDL_GL_UpdateRectsLock(SDL_VideoDevice* this, int numrects, SDL_Rect *rects)
  1377 {
  1378 	SDL_GL_Lock();
  1379  	SDL_GL_UpdateRects(numrects, rects);
  1380 	SDL_GL_Unlock();
  1381 }
  1382 
  1383 /* Update rects without state setting and changing (the caller is responsible for it) */
  1384 void SDL_GL_UpdateRects(int numrects, SDL_Rect *rects)
  1385 {
  1386 #ifdef HAVE_OPENGL
  1387 	SDL_VideoDevice *this = current_video;
  1388 	SDL_Rect update, tmp;
  1389 	int x, y, i;
  1390 
  1391 	for ( i = 0; i < numrects; i++ )
  1392 	{
  1393 		tmp.y = rects[i].y;
  1394 		tmp.h = rects[i].h;
  1395 		for ( y = 0; y <= rects[i].h / 256; y++ )
  1396 		{
  1397 			tmp.x = rects[i].x;
  1398 			tmp.w = rects[i].w;
  1399 			for ( x = 0; x <= rects[i].w / 256; x++ )
  1400 			{
  1401 				update.x = tmp.x;
  1402 				update.y = tmp.y;
  1403 				update.w = tmp.w;
  1404 				update.h = tmp.h;
  1405 
  1406 				if ( update.w > 256 )
  1407 					update.w = 256;
  1408 
  1409 				if ( update.h > 256 )
  1410 					update.h = 256;
  1411 			
  1412 				this->glFlush();
  1413 				this->glTexSubImage2D( 
  1414 					GL_TEXTURE_2D, 
  1415 					0, 
  1416 					0, 
  1417 					0, 
  1418 					update.w, 
  1419 					update.h, 
  1420 					this->is_32bit? GL_RGBA : GL_RGB,
  1421 #ifdef GL_VERSION_1_2
  1422 					this->is_32bit ? GL_UNSIGNED_BYTE : GL_UNSIGNED_SHORT_5_6_5,
  1423 #else
  1424 					GL_UNSIGNED_BYTE,
  1425 #endif
  1426 					(Uint8 *)this->screen->pixels + 
  1427 						this->screen->format->BytesPerPixel * update.x + 
  1428 						update.y * this->screen->pitch );
  1429 	
  1430 				this->glFlush();
  1431 				/*
  1432 				* Note the parens around the function name:
  1433 				* This is because some OpenGL implementations define glTexCoord etc 
  1434 				* as macros, and we don't want them expanded here.
  1435 				*/
  1436 				this->glBegin(GL_TRIANGLE_STRIP);
  1437 					(this->glTexCoord2f)( 0.0, 0.0 );	
  1438 					(this->glVertex2i)( update.x, update.y );
  1439 					(this->glTexCoord2f)( (float)(update.w / 256.0), 0.0 );	
  1440 					(this->glVertex2i)( update.x + update.w, update.y );
  1441 					(this->glTexCoord2f)( 0.0, (float)(update.h / 256.0) );
  1442 					(this->glVertex2i)( update.x, update.y + update.h );
  1443 					(this->glTexCoord2f)( (float)(update.w / 256.0), (float)(update.h / 256.0) );	
  1444 					(this->glVertex2i)( update.x + update.w	, update.y + update.h );
  1445 				this->glEnd();	
  1446 			
  1447 				tmp.x += 256;
  1448 				tmp.w -= 256;
  1449 			}
  1450 			tmp.y += 256;
  1451 			tmp.h -= 256;
  1452 		}
  1453 	}
  1454 #endif
  1455 }
  1456 
  1457 /* Lock == save current state */
  1458 void SDL_GL_Lock()
  1459 {
  1460 #ifdef HAVE_OPENGL
  1461 	lock_count--;
  1462 	if (lock_count==-1)
  1463 	{
  1464 		SDL_VideoDevice *this = current_video;
  1465 
  1466 		this->glPushAttrib( GL_ALL_ATTRIB_BITS );	/* TODO: narrow range of what is saved */
  1467 		this->glPushClientAttrib( GL_CLIENT_PIXEL_STORE_BIT );
  1468 
  1469 		this->glEnable(GL_TEXTURE_2D);
  1470 		this->glEnable(GL_BLEND);
  1471 		this->glDisable(GL_FOG);
  1472 		this->glDisable(GL_ALPHA_TEST);
  1473 		this->glDisable(GL_DEPTH_TEST);
  1474 		this->glDisable(GL_SCISSOR_TEST);	
  1475 		this->glDisable(GL_STENCIL_TEST);
  1476 		this->glDisable(GL_CULL_FACE);
  1477 
  1478 		this->glBindTexture( GL_TEXTURE_2D, this->texture );
  1479 		this->glTexEnvf( GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE );
  1480 		this->glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST );
  1481 		this->glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST );
  1482 		this->glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT );
  1483 		this->glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT );
  1484 
  1485 		this->glPixelStorei( GL_UNPACK_ROW_LENGTH, this->screen->pitch / this->screen->format->BytesPerPixel );
  1486 		this->glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
  1487 		(this->glColor4f)(1.0, 1.0, 1.0, 1.0);		/* Solaris workaround */
  1488 
  1489 		this->glViewport(0, 0, this->screen->w, this->screen->h);
  1490 		this->glMatrixMode(GL_PROJECTION);
  1491 		this->glPushMatrix();
  1492 		this->glLoadIdentity();
  1493 
  1494 		this->glOrtho(0.0, (GLdouble) this->screen->w, (GLdouble) this->screen->h, 0.0, 0.0, 1.0);
  1495 
  1496 		this->glMatrixMode(GL_MODELVIEW);
  1497 		this->glPushMatrix();
  1498 		this->glLoadIdentity();
  1499 	}
  1500 #endif
  1501 }
  1502 
  1503 /* Unlock == restore saved state */
  1504 void SDL_GL_Unlock()
  1505 {
  1506 #ifdef HAVE_OPENGL
  1507 	lock_count++;
  1508 	if (lock_count==0)
  1509 	{
  1510 		SDL_VideoDevice *this = current_video;
  1511 
  1512 		this->glPopMatrix();
  1513 		this->glMatrixMode(GL_PROJECTION);
  1514 		this->glPopMatrix();
  1515 
  1516 		this->glPopClientAttrib();
  1517 		this->glPopAttrib();
  1518 	}
  1519 #endif
  1520 }
  1521 
  1522 /*
  1523  * Sets/Gets the title and icon text of the display window, if any.
  1524  */
  1525 void SDL_WM_SetCaption (const char *title, const char *icon)
  1526 {
  1527 	SDL_VideoDevice *video = current_video;
  1528 	SDL_VideoDevice *this  = current_video;
  1529 
  1530 	if ( title ) {
  1531 		if ( wm_title ) {
  1532 			free(wm_title);
  1533 		}
  1534 		wm_title = (char *)malloc(strlen(title)+1);
  1535 		if ( wm_title != NULL ) {
  1536 			strcpy(wm_title, title);
  1537 		}
  1538 	}
  1539 	if ( icon ) {
  1540 		if ( wm_icon ) {
  1541 			free(wm_icon);
  1542 		}
  1543 		wm_icon = (char *)malloc(strlen(icon)+1);
  1544 		if ( wm_icon != NULL ) {
  1545 			strcpy(wm_icon, icon);
  1546 		}
  1547 	}
  1548 	if ( (title || icon) && video && (video->SetCaption != NULL) ) {
  1549 		video->SetCaption(this, wm_title, wm_icon);
  1550 	}
  1551 }
  1552 void SDL_WM_GetCaption (char **title, char **icon)
  1553 {
  1554 	if ( title ) {
  1555 		*title = wm_title;
  1556 	}
  1557 	if ( icon ) {
  1558 		*icon = wm_icon;
  1559 	}
  1560 }
  1561 
  1562 /* Utility function used by SDL_WM_SetIcon() */
  1563 static void CreateMaskFromColorKey(SDL_Surface *icon, Uint8 *mask)
  1564 {
  1565 	int x, y;
  1566 	Uint32 colorkey;
  1567 #define SET_MASKBIT(icon, x, y, mask) \
  1568 	mask[(y*((icon->w+7)/8))+(x/8)] &= ~(0x01<<(7-(x%8)))
  1569 
  1570 	colorkey = icon->format->colorkey;
  1571 	switch (icon->format->BytesPerPixel) {
  1572 		case 1: { Uint8 *pixels;
  1573 			for ( y=0; y<icon->h; ++y ) {
  1574 				pixels = (Uint8 *)icon->pixels + y*icon->pitch;
  1575 				for ( x=0; x<icon->w; ++x ) {
  1576 					if ( *pixels++ == colorkey ) {
  1577 						SET_MASKBIT(icon, x, y, mask);
  1578 					}
  1579 				}
  1580 			}
  1581 		}
  1582 		break;
  1583 
  1584 		case 2: { Uint16 *pixels;
  1585 			for ( y=0; y<icon->h; ++y ) {
  1586 				pixels = (Uint16 *)icon->pixels +
  1587 				                   y*icon->pitch/2;
  1588 				for ( x=0; x<icon->w; ++x ) {
  1589 					if ( *pixels++ == colorkey ) {
  1590 						SET_MASKBIT(icon, x, y, mask);
  1591 					}
  1592 				}
  1593 			}
  1594 		}
  1595 		break;
  1596 
  1597 		case 4: { Uint32 *pixels;
  1598 			for ( y=0; y<icon->h; ++y ) {
  1599 				pixels = (Uint32 *)icon->pixels +
  1600 				                   y*icon->pitch/4;
  1601 				for ( x=0; x<icon->w; ++x ) {
  1602 					if ( *pixels++ == colorkey ) {
  1603 						SET_MASKBIT(icon, x, y, mask);
  1604 					}
  1605 				}
  1606 			}
  1607 		}
  1608 		break;
  1609 	}
  1610 }
  1611 
  1612 /*
  1613  * Sets the window manager icon for the display window.
  1614  */
  1615 void SDL_WM_SetIcon (SDL_Surface *icon, Uint8 *mask)
  1616 {
  1617 	SDL_VideoDevice *video = current_video;
  1618 	SDL_VideoDevice *this  = current_video;
  1619 
  1620 	if ( icon && video->SetIcon ) {
  1621 		/* Generate a mask if necessary, and create the icon! */
  1622 		if ( mask == NULL ) {
  1623 			int mask_len = icon->h*(icon->w+7)/8;
  1624 			mask = (Uint8 *)malloc(mask_len);
  1625 			if ( mask == NULL ) {
  1626 				return;
  1627 			}
  1628 			memset(mask, ~0, mask_len);
  1629 			if ( icon->flags & SDL_SRCCOLORKEY ) {
  1630 				CreateMaskFromColorKey(icon, mask);
  1631 			}
  1632 			video->SetIcon(video, icon, mask);
  1633 			free(mask);
  1634 		} else {
  1635 			video->SetIcon(this, icon, mask);
  1636 		}
  1637 	}
  1638 }
  1639 
  1640 /*
  1641  * Grab or ungrab the keyboard and mouse input.
  1642  * This function returns the final grab mode after calling the
  1643  * driver dependent function.
  1644  */
  1645 static SDL_GrabMode SDL_WM_GrabInputRaw(SDL_GrabMode mode)
  1646 {
  1647 	SDL_VideoDevice *video = current_video;
  1648 	SDL_VideoDevice *this  = current_video;
  1649 
  1650 	/* Only do something if we have support for grabs */
  1651 	if ( video->GrabInput == NULL ) {
  1652 		return(video->input_grab);
  1653 	}
  1654 
  1655 	/* If the final grab mode if off, only then do we actually grab */
  1656 #ifdef DEBUG_GRAB
  1657   printf("SDL_WM_GrabInputRaw(%d) ... ", mode);
  1658 #endif
  1659 	if ( mode == SDL_GRAB_OFF ) {
  1660 		if ( video->input_grab != SDL_GRAB_OFF ) {
  1661 			mode = video->GrabInput(this, mode);
  1662 		}
  1663 	} else {
  1664 		if ( video->input_grab == SDL_GRAB_OFF ) {
  1665 			mode = video->GrabInput(this, mode);
  1666 		}
  1667 	}
  1668 	if ( mode != video->input_grab ) {
  1669 		video->input_grab = mode;
  1670 		if ( video->CheckMouseMode ) {
  1671 			video->CheckMouseMode(this);
  1672 		}
  1673 	}
  1674 #ifdef DEBUG_GRAB
  1675   printf("Final mode %d\n", video->input_grab);
  1676 #endif
  1677 
  1678 	/* Return the final grab state */
  1679 	if ( mode >= SDL_GRAB_FULLSCREEN ) {
  1680 		mode -= SDL_GRAB_FULLSCREEN;
  1681 	}
  1682 	return(mode);
  1683 }
  1684 SDL_GrabMode SDL_WM_GrabInput(SDL_GrabMode mode)
  1685 {
  1686 	SDL_VideoDevice *video = current_video;
  1687 
  1688 	/* If the video isn't initialized yet, we can't do anything */
  1689 	if ( ! video ) {
  1690 		return SDL_GRAB_OFF;
  1691 	}
  1692 
  1693 	/* Return the current mode on query */
  1694 	if ( mode == SDL_GRAB_QUERY ) {
  1695 		mode = video->input_grab;
  1696 		if ( mode >= SDL_GRAB_FULLSCREEN ) {
  1697 			mode -= SDL_GRAB_FULLSCREEN;
  1698 		}
  1699 		return(mode);
  1700 	}
  1701 
  1702 #ifdef DEBUG_GRAB
  1703   printf("SDL_WM_GrabInput(%d) ... ", mode);
  1704 #endif
  1705 	/* If the video surface is fullscreen, we always grab */
  1706 	if ( mode >= SDL_GRAB_FULLSCREEN ) {
  1707 		mode -= SDL_GRAB_FULLSCREEN;
  1708 	}
  1709 	if ( SDL_VideoSurface && (SDL_VideoSurface->flags & SDL_FULLSCREEN) ) {
  1710 		mode += SDL_GRAB_FULLSCREEN;
  1711 	}
  1712 	return(SDL_WM_GrabInputRaw(mode));
  1713 }
  1714 static SDL_GrabMode SDL_WM_GrabInputOff(void)
  1715 {
  1716 	SDL_GrabMode mode;
  1717 
  1718 	/* First query the current grab state */
  1719 	mode = SDL_WM_GrabInput(SDL_GRAB_QUERY);
  1720 
  1721 	/* Now explicitly turn off input grab */
  1722 	SDL_WM_GrabInputRaw(SDL_GRAB_OFF);
  1723 
  1724 	/* Return the old state */
  1725 	return(mode);
  1726 }
  1727 
  1728 /*
  1729  * Iconify the window in window managed environments.
  1730  * A successful iconification will result in an SDL_APPACTIVE loss event.
  1731  */
  1732 int SDL_WM_IconifyWindow(void)
  1733 {
  1734 	SDL_VideoDevice *video = current_video;
  1735 	SDL_VideoDevice *this  = current_video;
  1736 	int retval;
  1737 
  1738 	retval = 0;
  1739 	if ( video->IconifyWindow ) {
  1740 		retval = video->IconifyWindow(this);
  1741 	}
  1742 	return(retval);
  1743 }
  1744 
  1745 /*
  1746  * Toggle fullscreen mode
  1747  */
  1748 int SDL_WM_ToggleFullScreen(SDL_Surface *surface)
  1749 {
  1750 	SDL_VideoDevice *video = current_video;
  1751 	SDL_VideoDevice *this  = current_video;
  1752 	int toggled;
  1753 
  1754 	toggled = 0;
  1755 	if ( SDL_PublicSurface && (surface == SDL_PublicSurface) &&
  1756 	     video->ToggleFullScreen ) {
  1757 		if ( surface->flags & SDL_FULLSCREEN ) {
  1758 			toggled = video->ToggleFullScreen(this, 0);
  1759 			if ( toggled ) {
  1760 				SDL_VideoSurface->flags &= ~SDL_FULLSCREEN;
  1761 				SDL_PublicSurface->flags &= ~SDL_FULLSCREEN;
  1762 			}
  1763 		} else {
  1764 			toggled = video->ToggleFullScreen(this, 1);
  1765 			if ( toggled ) {
  1766 				SDL_VideoSurface->flags |= SDL_FULLSCREEN;
  1767 				SDL_PublicSurface->flags |= SDL_FULLSCREEN;
  1768 			}
  1769 		}
  1770 		/* Double-check the grab state inside SDL_WM_GrabInput() */
  1771 		if ( toggled ) {
  1772 			SDL_WM_GrabInput(video->input_grab);
  1773 		}
  1774 	}
  1775 	return(toggled);
  1776 }
  1777 
  1778 /*
  1779  * Get some platform dependent window manager information
  1780  */
  1781 int SDL_GetWMInfo (SDL_SysWMinfo *info)
  1782 {
  1783 	SDL_VideoDevice *video = current_video;
  1784 	SDL_VideoDevice *this  = current_video;
  1785 
  1786 	if ( video && video->GetWMInfo ) {
  1787 		return(video->GetWMInfo(this, info));
  1788 	} else {
  1789 		return(0);
  1790 	}
  1791 }